Merge branch 'revert-definition-map-lookup' into release
diff --git a/.gitattributes b/.gitattributes
index d21f1dd..d3f7280 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -12,6 +12,8 @@
 *.dsp           -crlf
 *.dsptemplate   -crlf
 *.dsw           -crlf
+*.pfx           -crlf
+*.png           -crlf
 *.sln           -crlf
 *.vcproj        -crlf
 
diff --git a/Auxiliary/bash-completion/ctest b/Auxiliary/bash-completion/ctest
index 25cb998..327e12c 100644
--- a/Auxiliary/bash-completion/ctest
+++ b/Auxiliary/bash-completion/ctest
@@ -19,8 +19,12 @@
             _filedir
             return
             ;;
-        -L|--label-regex|-LE|--label-exclude|--track|-I|--tests-information|\
-        --max-width|--timeout|--stop-time)
+        -L|--label-regex|-LE|--label-exclude)
+            COMPREPLY=( $( compgen -W '$( ctest --print-labels 2>/dev/null |
+                grep "^  " 2>/dev/null | cut -d" " -f 3 )' -- "$cur" ) )
+            return
+            ;;
+        --track|-I|--tests-information|--max-width|--timeout|--stop-time)
             # argument required but no completions available
             return
             ;;
diff --git a/Auxiliary/cmake-syntax.vim b/Auxiliary/cmake-syntax.vim
index 80395ab..782130d 100644
--- a/Auxiliary/cmake-syntax.vim
+++ b/Auxiliary/cmake-syntax.vim
@@ -48,9 +48,9 @@
 syn keyword cmakeDeprecated ABSTRACT_FILES BUILD_NAME SOURCE_FILES SOURCE_FILES_REMOVE VTK_MAKE_INSTANTIATOR VTK_WRAP_JAVA VTK_WRAP_PYTHON VTK_WRAP_TCL WRAP_EXCLUDE_FILES
            \ nextgroup=cmakeArguments
 
-" The keywords are generated as:  cmake --help-command-list | tr "\n" " "
+" The keywords are generated as:  cmake --help-command-list | tr "\n" " " | tr "[:lower:]" "[:upper:]"
 syn keyword cmakeStatement
-      \ ADD_CUSTOM_COMMAND ADD_CUSTOM_TARGET ADD_DEFINITIONS ADD_DEPENDENCIES ADD_EXECUTABLE ADD_LIBRARY ADD_SUBDIRECTORY ADD_TEST AUX_SOURCE_DIRECTORY BUILD_COMMAND BUILD_NAME CMAKE_MINIMUM_REQUIRED CONFIGURE_FILE CREATE_TEST_SOURCELIST ELSE ELSEIF ENABLE_LANGUAGE ENABLE_TESTING ENDFOREACH ENDFUNCTION ENDIF ENDMACRO ENDWHILE EXEC_PROGRAM EXECUTE_PROCESS EXPORT_LIBRARY_DEPENDENCIES FILE FIND_FILE FIND_LIBRARY FIND_PACKAGE FIND_PATH FIND_PROGRAM FLTK_WRAP_UI FOREACH FUNCTION GET_CMAKE_PROPERTY GET_DIRECTORY_PROPERTY GET_FILENAME_COMPONENT GET_SOURCE_FILE_PROPERTY GET_TARGET_PROPERTY GET_TEST_PROPERTY IF INCLUDE INCLUDE_DIRECTORIES INCLUDE_EXTERNAL_MSPROJECT INCLUDE_REGULAR_EXPRESSION INSTALL INSTALL_FILES INSTALL_PROGRAMS INSTALL_TARGETS LINK_DIRECTORIES LINK_LIBRARIES LIST LOAD_CACHE LOAD_COMMAND MACRO MAKE_DIRECTORY MARK_AS_ADVANCED MATH MESSAGE OPTION OUTPUT_REQUIRED_FILES PROJECT QT_WRAP_CPP QT_WRAP_UI REMOVE REMOVE_DEFINITIONS SEPARATE_ARGUMENTS SET SET_DIRECTORY_PROPERTIES SET_SOURCE_FILES_PROPERTIES SET_TARGET_PROPERTIES SET_TESTS_PROPERTIES SITE_NAME SOURCE_GROUP STRING SUBDIR_DEPENDS SUBDIRS TARGET_LINK_LIBRARIES TRY_COMPILE TRY_RUN UNSET USE_MANGLED_MESA UTILITY_SOURCE VARIABLE_REQUIRES VTK_MAKE_INSTANTIATOR VTK_WRAP_JAVA VTK_WRAP_PYTHON VTK_WRAP_TCL WHILE WRITE_FILE
+            \ ADD_COMPILE_OPTIONS ADD_CUSTOM_COMMAND ADD_CUSTOM_TARGET ADD_DEFINITIONS ADD_DEPENDENCIES ADD_EXECUTABLE ADD_LIBRARY ADD_SUBDIRECTORY ADD_TEST AUX_SOURCE_DIRECTORY BREAK BUILD_COMMAND BUILD_NAME CMAKE_HOST_SYSTEM_INFORMATION CMAKE_MINIMUM_REQUIRED CMAKE_POLICY CONFIGURE_FILE CREATE_TEST_SOURCELIST CTEST_BUILD CTEST_CONFIGURE CTEST_COVERAGE CTEST_EMPTY_BINARY_DIRECTORY CTEST_MEMCHECK CTEST_READ_CUSTOM_FILES CTEST_RUN_SCRIPT CTEST_SLEEP CTEST_START CTEST_SUBMIT CTEST_TEST CTEST_UPDATE CTEST_UPLOAD DEFINE_PROPERTY ELSE ELSEIF ENABLE_LANGUAGE ENABLE_TESTING ENDFOREACH ENDFUNCTION ENDIF ENDMACRO ENDWHILE EXEC_PROGRAM EXECUTE_PROCESS EXPORT EXPORT_LIBRARY_DEPENDENCIES FILE FIND_FILE FIND_LIBRARY FIND_PACKAGE FIND_PATH FIND_PROGRAM FLTK_WRAP_UI FOREACH FUNCTION GET_CMAKE_PROPERTY GET_DIRECTORY_PROPERTY GET_FILENAME_COMPONENT GET_PROPERTY GET_SOURCE_FILE_PROPERTY GET_TARGET_PROPERTY GET_TEST_PROPERTY IF INCLUDE INCLUDE_DIRECTORIES INCLUDE_EXTERNAL_MSPROJECT INCLUDE_REGULAR_EXPRESSION INSTALL INSTALL_FILES INSTALL_PROGRAMS INSTALL_TARGETS LINK_DIRECTORIES LINK_LIBRARIES LIST LOAD_CACHE LOAD_COMMAND MACRO MAKE_DIRECTORY MARK_AS_ADVANCED MATH MESSAGE OPTION OUTPUT_REQUIRED_FILES PROJECT QT_WRAP_CPP QT_WRAP_UI REMOVE REMOVE_DEFINITIONS RETURN SEPARATE_ARGUMENTS SET SET_DIRECTORY_PROPERTIES SET_PROPERTY SET_SOURCE_FILES_PROPERTIES SET_TARGET_PROPERTIES SET_TESTS_PROPERTIES SITE_NAME SOURCE_GROUP STRING SUBDIR_DEPENDS SUBDIRS TARGET_COMPILE_DEFINITIONS TARGET_COMPILE_FEATURES TARGET_COMPILE_OPTIONS TARGET_INCLUDE_DIRECTORIES TARGET_LINK_LIBRARIES TARGET_SOURCES TRY_COMPILE TRY_RUN UNSET USE_MANGLED_MESA UTILITY_SOURCE VARIABLE_REQUIRES VARIABLE_WATCH WHILE WRITE_FILE
             \ nextgroup=cmakeArguments
 syn keyword cmakeTodo
             \ TODO FIXME XXX
diff --git a/CMakeCPack.cmake b/CMakeCPack.cmake
index fb55bfc..22ca8cf 100644
--- a/CMakeCPack.cmake
+++ b/CMakeCPack.cmake
@@ -50,7 +50,7 @@
   if(NOT DEFINED CPACK_SYSTEM_NAME)
     # make sure package is not Cygwin-unknown, for Cygwin just
     # cygwin is good for the system name
-    if("${CMAKE_SYSTEM_NAME}" STREQUAL "CYGWIN")
+    if("x${CMAKE_SYSTEM_NAME}" STREQUAL "xCYGWIN")
       set(CPACK_SYSTEM_NAME Cygwin)
     else()
       set(CPACK_SYSTEM_NAME ${CMAKE_SYSTEM_NAME}-${CMAKE_SYSTEM_PROCESSOR})
@@ -59,11 +59,37 @@
   if(${CPACK_SYSTEM_NAME} MATCHES Windows)
     if(CMAKE_CL_64)
       set(CPACK_SYSTEM_NAME win64-x64)
+      set(CPACK_IFW_TARGET_DIRECTORY "@RootDir@/Program Files/${CMAKE_PROJECT_NAME}")
     else()
       set(CPACK_SYSTEM_NAME win32-x86)
     endif()
   endif()
 
+  if(${CMAKE_SYSTEM_NAME} MATCHES Windows)
+    set(_CPACK_IFW_PACKAGE_ICON
+        "set(CPACK_IFW_PACKAGE_ICON \"${CMake_SOURCE_DIR}/Source/QtDialog/CMakeSetup.ico\")")
+    if(BUILD_QtDialog)
+      set(_CPACK_IFW_SHORTCUT_OPTIONAL "${_CPACK_IFW_SHORTCUT_OPTIONAL}component.addOperation(\"CreateShortcut\", \"@TargetDir@/bin/cmake-gui.exe\", \"@StartMenuDir@/CMake (cmake-gui).lnk\");\n")
+    endif()
+    if(SPHINX_HTML)
+      set(_CPACK_IFW_SHORTCUT_OPTIONAL "${_CPACK_IFW_SHORTCUT_OPTIONAL}component.addOperation(\"CreateShortcut\", \"@TargetDir@/doc/cmake-${CMake_VERSION_MAJOR}.${CMake_VERSION_MINOR}/html/index.html\", \"@StartMenuDir@/CMake Documentation.lnk\");\n")
+    endif()
+    configure_file("${CMake_SOURCE_DIR}/Source/QtIFW/installscript.qs.in"
+      "${CMake_BINARY_DIR}/installscript.qs" @ONLY
+    )
+    install(FILES "${CMake_SOURCE_DIR}/Source/QtIFW/cmake.org.html"
+      DESTINATION "."
+    )
+    set(_CPACK_IFW_PACKAGE_SCRIPT "set(CPACK_IFW_COMPONENT_GROUP_CMAKE_SCRIPT \"${CMake_BINARY_DIR}/installscript.qs\")")
+  endif()
+
+  if(${CMAKE_SYSTEM_NAME} MATCHES Linux)
+    set(CPACK_IFW_TARGET_DIRECTORY "@HomeDir@/${CMAKE_PROJECT_NAME}")
+    set(CPACK_IFW_ADMIN_TARGET_DIRECTORY "@ApplicationsDir@/${CMAKE_PROJECT_NAME}")
+  endif()
+
+  set(_CPACK_IFW_PACKAGE_VERSION ${CMake_VERSION_MAJOR}.${CMake_VERSION_MINOR}.${CMake_VERSION_PATCH})
+
   if(NOT DEFINED CPACK_PACKAGE_FILE_NAME)
     # if the CPACK_PACKAGE_FILE_NAME is not defined by the cache
     # default to source package - system, on cygwin system is not
diff --git a/CMakeCPackOptions.cmake.in b/CMakeCPackOptions.cmake.in
index aba404f..57ed4ca 100644
--- a/CMakeCPackOptions.cmake.in
+++ b/CMakeCPackOptions.cmake.in
@@ -31,6 +31,28 @@
 # they might not if qt was not enabled for the build
 include("@QT_DIALOG_CPACK_OPTIONS_FILE@" OPTIONAL)
 
+if(CPACK_GENERATOR MATCHES "IFW")
+  # Installer configuration
+  set(CPACK_IFW_PACKAGE_TITLE "CMake Build Tool")
+  set(CPACK_IFW_PRODUCT_URL "http://www.cmake.org")
+  @_CPACK_IFW_PACKAGE_ICON@
+  set(CPACK_IFW_PACKAGE_WINDOW_ICON
+    "@CMake_SOURCE_DIR@/Source/QtDialog/CMakeSetup128.png")
+  # Package configuration group
+  set(CPACK_IFW_PACKAGE_GROUP CMake)
+  # Group configuration
+  set(CPACK_COMPONENT_GROUP_CMAKE_DISPLAY_NAME
+    "@CPACK_PACKAGE_NAME@")
+  set(CPACK_COMPONENT_GROUP_CMAKE_DESCRIPTION
+    "@CPACK_PACKAGE_DESCRIPTION_SUMMARY@")
+  # IFW group configuration
+  set(CPACK_IFW_COMPONENT_GROUP_CMAKE_VERSION
+    "@_CPACK_IFW_PACKAGE_VERSION@")
+  set(CPACK_IFW_COMPONENT_GROUP_CMAKE_LICENSES
+    "@CPACK_PACKAGE_NAME@ Copyright" "@CPACK_RESOURCE_FILE_LICENSE@")
+  @_CPACK_IFW_PACKAGE_SCRIPT@
+endif()
+
 if(CPACK_GENERATOR MATCHES "CygwinSource")
   # when packaging source make sure the .build directory is not included
     set(CPACK_SOURCE_IGNORE_FILES
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 5e4cd15..71850de 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -57,7 +57,7 @@
 
   # Allow the user to enable/disable all system utility library options by
   # defining CMAKE_USE_SYSTEM_LIBRARIES or CMAKE_USE_SYSTEM_LIBRARY_${util}.
-  set(UTILITIES BZIP2 CURL EXPAT LIBARCHIVE ZLIB)
+  set(UTILITIES BZIP2 CURL EXPAT LIBARCHIVE LIBLZMA ZLIB)
   foreach(util ${UTILITIES})
     if(NOT DEFINED CMAKE_USE_SYSTEM_LIBRARY_${util}
         AND DEFINED CMAKE_USE_SYSTEM_LIBRARIES)
@@ -93,6 +93,8 @@
     "${CMAKE_USE_SYSTEM_LIBRARY_ZLIB}" "NOT CMAKE_USE_SYSTEM_LIBARCHIVE;NOT CMAKE_USE_SYSTEM_CURL" ON)
   CMAKE_DEPENDENT_OPTION(CMAKE_USE_SYSTEM_BZIP2 "Use system-installed bzip2"
     "${CMAKE_USE_SYSTEM_LIBRARY_BZIP2}" "NOT CMAKE_USE_SYSTEM_LIBARCHIVE" ON)
+  CMAKE_DEPENDENT_OPTION(CMAKE_USE_SYSTEM_LIBLZMA "Use system-installed liblzma"
+    "${CMAKE_USE_SYSTEM_LIBRARY_LIBLZMA}" "NOT CMAKE_USE_SYSTEM_LIBARCHIVE" ON)
 
   # Mention to the user what system libraries are being used.
   foreach(util ${UTILITIES})
@@ -201,12 +203,6 @@
 #-----------------------------------------------------------------------
 macro (CMAKE_BUILD_UTILITIES)
   #---------------------------------------------------------------------
-  # Create the KWIML library for CMake.
-  set(KWIML cmIML)
-  set(KWIML_HEADER_ROOT ${CMake_BINARY_DIR}/Utilities)
-  add_subdirectory(Utilities/KWIML)
-
-  #---------------------------------------------------------------------
   # Create the kwsys library for CMake.
   set(KWSYS_NAMESPACE cmsys)
   set(KWSYS_USE_SystemTools 1)
@@ -307,6 +303,23 @@
   endif()
 
   #---------------------------------------------------------------------
+  # Build or use system liblzma for libarchive.
+  if(CMAKE_USE_SYSTEM_LIBLZMA)
+    find_package(LibLZMA)
+    if(NOT LIBLZMA_FOUND)
+      message(FATAL_ERROR "CMAKE_USE_SYSTEM_LIBLZMA is ON but LibLZMA is not found!")
+    endif()
+    set(LZMA_INCLUDE_DIR ${LIBLZMA_INCLUDE_DIRS})
+    set(LZMA_LIBRARY ${LIBLZMA_LIBRARIES})
+  else()
+    add_subdirectory(Utilities/cmliblzma)
+    CMAKE_SET_TARGET_FOLDER(cmliblzma "Utilities/3rdParty")
+    set(LZMA_INCLUDE_DIR
+      "${CMAKE_CURRENT_SOURCE_DIR}/Utilities/cmliblzma/liblzma/api")
+    set(LZMA_LIBRARY cmliblzma)
+  endif()
+
+  #---------------------------------------------------------------------
   # Build or use system libarchive for CMake and CTest.
   if(CMAKE_USE_SYSTEM_LIBARCHIVE)
     find_package(LibArchive)
@@ -321,7 +334,7 @@
     add_definitions(-DLIBARCHIVE_STATIC)
     set(ENABLE_NETTLE OFF CACHE INTERNAL "Enable use of Nettle")
     set(ENABLE_OPENSSL ${CMAKE_USE_OPENSSL} CACHE INTERNAL "Enable use of OpenSSL")
-    set(ENABLE_LZMA OFF CACHE INTERNAL "Enable the use of the system found LZMA library if found")
+    set(ENABLE_LZMA ON CACHE INTERNAL "Enable the use of the system found LZMA library if found")
     set(ENABLE_ZLIB ON CACHE INTERNAL "Enable the use of the system found ZLIB library if found")
     set(ENABLE_BZip2 ON CACHE INTERNAL "Enable the use of the system found BZip2 library if found")
     set(ENABLE_EXPAT OFF CACHE INTERNAL "Enable the use of the system found EXPAT library if found")
@@ -368,7 +381,7 @@
   # Use curses?
   if (UNIX)
     # there is a bug in the Syllable libraries which makes linking ccmake fail, Alex
-    if(NOT "${CMAKE_SYSTEM_NAME}" MATCHES syllable)
+    if(NOT CMAKE_SYSTEM_NAME MATCHES syllable)
       set(CURSES_NEED_NCURSES TRUE)
       find_package(Curses QUIET)
       if (CURSES_LIBRARY)
@@ -451,7 +464,7 @@
 # CMAKE_TESTS_CDASH_SERVER: CDash server used by CMake/Tests.
 #
 # If not defined or "", this variable defaults to the server at
-# http://www.cdash.org/CDash.
+# "http://open.cdash.org".
 #
 # If set explicitly to "NOTFOUND", curl tests and ctest tests that use
 # the network are skipped.
@@ -462,9 +475,14 @@
 # should be run first.
 #
 if("x${CMAKE_TESTS_CDASH_SERVER}" STREQUAL "x")
-  set(CMAKE_TESTS_CDASH_SERVER "http://www.cdash.org/CDash")
+  set(CMAKE_TESTS_CDASH_SERVER "http://open.cdash.org")
 endif()
 
+# Create the KWIML library for CMake.
+set(KWIML cmIML)
+set(KWIML_HEADER_ROOT ${CMake_BINARY_DIR}/Utilities)
+add_subdirectory(Utilities/KWIML)
+
 if(NOT CMake_TEST_EXTERNAL_CMAKE)
   # build the utilities (a macro defined in this file)
   CMAKE_BUILD_UTILITIES()
@@ -534,10 +552,6 @@
 
 # setup some Testing support (a macro defined in this file)
 CMAKE_SETUP_TESTING()
-configure_file(
-  "${CMAKE_CURRENT_SOURCE_DIR}/DartLocal.conf.in"
-  "${CMAKE_CURRENT_BINARY_DIR}/DartLocal.conf"
-  COPYONLY)
 
 if(NOT CMake_TEST_EXTERNAL_CMAKE)
   if(NOT CMake_VERSION_IS_RELEASE)
diff --git a/CTestConfig.cmake b/CTestConfig.cmake
index 819f9ba..df2f94c 100644
--- a/CTestConfig.cmake
+++ b/CTestConfig.cmake
@@ -13,8 +13,8 @@
 set(CTEST_NIGHTLY_START_TIME "1:00:00 UTC")
 
 set(CTEST_DROP_METHOD "http")
-set(CTEST_DROP_SITE "www.cdash.org")
-set(CTEST_DROP_LOCATION "/CDash/submit.php?project=CMake")
+set(CTEST_DROP_SITE "open.cdash.org")
+set(CTEST_DROP_LOCATION "/submit.php?project=CMake")
 set(CTEST_DROP_SITE_CDASH TRUE)
 set(CTEST_CDASH_VERSION "1.6")
 set(CTEST_CDASH_QUERY_VERSION TRUE)
diff --git a/DartConfig.cmake b/DartConfig.cmake
index 37f66c7..92dffca 100644
--- a/DartConfig.cmake
+++ b/DartConfig.cmake
@@ -13,6 +13,6 @@
 set(CTEST_NIGHTLY_START_TIME "21:00:00 EDT")
 
 set(CTEST_DROP_METHOD "http")
-set(CTEST_DROP_SITE "www.cdash.org")
-set(CTEST_DROP_LOCATION "/CDash/submit.php?project=CMake")
+set(CTEST_DROP_SITE "open.cdash.org")
+set(CTEST_DROP_LOCATION "/submit.php?project=CMake")
 set(CTEST_DROP_SITE_CDASH TRUE)
diff --git a/DartLocal.conf.in b/DartLocal.conf.in
deleted file mode 100644
index e28cb18..0000000
--- a/DartLocal.conf.in
+++ /dev/null
@@ -1,121 +0,0 @@
-ExpectedBuilds: \
-{andoria.kitware Linux-g++3.4-KDevelop} \
-{andoria.kitware Linux-g++3.4-SVN} \
-{DASH1.kitware Win32-nmake71} \
-{DASH1.kitware Win32-vs71} \
-{DASH1.kitware Win32-vs71Rel} \
-{DASH1.kitware zRel24-Win32-nmake71} \
-{DASH1.kitware zRel24-Win32-vs71} \
-{DASH11.kitware zRel24-Win32-nmake71} \
-{dash14.kitware Win32-bcc5.6} \
-{dash14.kitware Win32-cygwin} \
-{dash14.kitware Win32-mingw} \
-{dash14.kitware zRel24-Win32-bcc5.6} \
-{dash17.kitware Linux-g++4.0} \
-{dash1win64.kitware Win64-vs80} \
-{dash1win98.kitware Win32-vs60} \
-{DASH2.kitware Win32-nmake70} \
-{DASH2.kitware Win32-vs70} \
-{DASH2.kitware Win32-vs70-InPlace} \
-{DASH2.kitware zRel24-Win32-nmake70} \
-{DASH2.kitware zRel24-Win32-vs70} \
-{DASH3.kitware Win32-nmake60} \
-{DASH3.kitware Win32-vs60} \
-{DASH3.kitware zRel24-Win32-nmake60} \
-{DASH3.kitware zRel24-Win32-vs60} \
-{dash4.kitware Win32-bcc5.8} \
-{DASH5.kitware Linux-gcc332-InPlace} \
-{DASH5.kitware zRel24-Linix-gcc332} \
-{DASH6.kitware zRel24-Linix-gcc332} \
-{dash8.kitware Linux64-g++} \
-{dash8.kitware Linux64-g++332} \
-{dash8.kitware Linux64-g++341} \
-{dash8.kitware zRel24-Linux64-g++} \
-{dash8.kitware zRel24-Linux64-g++332} \
-{dashmacmini1.kitware Darwin-Tiger-Xcode21} \
-{dashmacmini1.kitware zRel24-Darwin-Tiger-g++} \
-{dashmacmini2.kitware DarwinIntel-g++} \
-{dashmacmini2.kitware DarwinIntel-Universal} \
-{dashmacmini2.kitware Darwin-Tiger-Xcode21-univ} \
-{dashmacmini3.kitware Darwin-LeopardIntel-g++} \
-{dashmacmini3.kitware Darwin-LeopardIntel-Universal} \
-{dashmacmini3.kitware Darwin-Leopard-Xcode21-univ} \
-{dashsgi1.kitware IRIX32-CC} \
-{dashsgi1.kitware IRIX64-CC} \
-{dashsun1.kitware SunOS-CC} \
-{dashsun1.kitware SunOS-CC-64} \
-{dashsun1.kitware SunOS-gcc34-64} \
-{destiny.kitware HP-UX-aCC} \
-{destiny.kitware HP-UX-aCC-gmake} \
-{devqnx.acfr.usyd.edu.au qnx-V3.3.5-gcc_ntox86} \
-{grayson.kitware Win32-nmake80} \
-{heart HP-UXia64-aCC} \
-{hythloth.kitware Linux64-bullseye-cov} \
-{hythloth.kitware Linux64-suncc-5.9} \
-{hythloth.kitware Linux-nightly-win32-release} \
-{insight.journal.kitware KWStyle} \
-{iris.elemtech IRIX64-CC64-7.4} \
-{iris.elemtech IRIX64-CC-7.4} \
-{JET.kitware Linux-valgrind2} \
-{krondor.kitware Darwin-c++} \
-{krondor.kitware zRel24-Darwin-c++} \
-{midworld.kitware DarwinG5-g++} \
-{midworld.kitware DarwinG5-XCode15} \
-{midworld.kitware zRel24-DarwinG5-g++} \
-{pre.vision.cs.rpi.edu FreeBSD-CC-gmake} \
-{pre.vision.cs.rpi.edu FreeBSD-CC-make} \
-{RogueResearch3 Mac10.5-CMake-gcc-dbg-ppc} \
-{RogueResearch3 Mac10.5-CMake-gcc-dbg-ppc64} \
-{RogueResearch3 Mac10.5-CMake-gcc-rel-ppc} \
-{RogueResearch3 Mac10.5-CMake-gcc-rel-ppc64} \
-{RogueResearch3 Mac10.5-CMake-Xcode-dbg-ppc} \
-{RogueResearch3 Mac10.5-CMake-Xcode-dbg-ppc64} \
-{RogueResearch4 Mac10.5-CMake-gcc-dbg-i386} \
-{RogueResearch4 Mac10.5-CMake-gcc-dbg-rosetta} \
-{RogueResearch4 Mac10.5-CMake-gcc-rel-i386} \
-{tick.rz.uni-augsburg.de LinuxPPC-g++3.3} \
-{tick.rz.uni-augsburg.de LinuxPPC-g++3.4} \
-{trinsic.kitware Win32-mingw} \
-{r06n01.pbm.ihost.com AIX53-xlC} \
-{r06n01.pbm.ihost.com zRel24-AIX53-xlC} \
-{valhalla.kitware Win32-wcl386}
-
-#{devqnx.acfr.usyd.edu.au qnx-V3.3.5-gcc_ntox86 } \
-#{mr-orange.obtech.net gentoo-linux-x86\_64-gcc-4.0.2 } \
-#{G5.Nfsnet.Org Darwin8.3-gcc4} \
-
-# commas in names do not work for expected builds....
-
-#{G4.Nfsnet.Org Darwin-c++} \
-#{salmon.nlm.nih.gov Darwin8.7-gcc4} \
-
-#{crd.ge.com Solaris-gcc343} \
-#{crd.ge.com Linux-icc81} \
-#{crd.ge.com Windows-bcc32} \
-#{crd.ge.com Windows-nmake71} \
-#{crd.ge.com Windows-nmake60} \
-
-#{dash16.kitware Linux-g++4.0} \
-#{styx Linuxia64-g++} \
-#{crd.ge.com Cygwin-gcc344} \
-#{valhalla.kitware Win32-bccRel} \
-#{valhalla.kitware Win32-bcc} \
-#{valhalla.kitware Win32-g++} \
-#{valhalla.kitware Win32-nmake60} \
-#{valhalla.kitware Win32-nmake70} \
-#{valhalla.kitware Win32-vs60} \
-#{valhalla.kitware Win32-vs70}
-#{crd.ge.com FreeBSD-gcc321} \
-#{crd.ge.com Linux-gcc320} \
-
-#{cogattaca.kitware LinuxWin32-g++-Werror} \
-#{cogattaca.kitware LinuxWin32-g++} \
-
-#{dash8.kitware Win64-icl80} \
-#{dash8.kitware zLRB-Win64-icl80} \
-
-#{hythloth.kitware Linux-icc-8.1} \
-
-CompressionMode: ALL
-CompressionCommand: /bin/gzip
-CompressionType: gzip
diff --git a/Help/command/add_custom_command.rst b/Help/command/add_custom_command.rst
index 028ca5a..e8b7cc8 100644
--- a/Help/command/add_custom_command.rst
+++ b/Help/command/add_custom_command.rst
@@ -3,10 +3,12 @@
 
 Add a custom build rule to the generated build system.
 
-There are two main signatures for add_custom_command The first
-signature is for adding a custom command to produce an output.
+There are two main signatures for ``add_custom_command``.
 
-::
+Generating Files
+^^^^^^^^^^^^^^^^
+
+The first signature is for adding a custom command to produce an output::
 
   add_custom_command(OUTPUT output1 [output2 ...]
                      COMMAND command1 [ARGS] [args1...]
@@ -18,28 +20,121 @@
                      [WORKING_DIRECTORY dir]
                      [COMMENT comment] [VERBATIM] [APPEND])
 
-This defines a command to generate specified OUTPUT file(s).  A target
-created in the same directory (CMakeLists.txt file) that specifies any
-output of the custom command as a source file is given a rule to
-generate the file using the command at build time.  Do not list the
-output in more than one independent target that may build in parallel
-or the two instances of the rule may conflict (instead use
-add_custom_target to drive the command and make the other targets
-depend on that one).  If an output name is a relative path it will be
-interpreted relative to the build tree directory corresponding to the
-current source directory.  Note that MAIN_DEPENDENCY is completely
-optional and is used as a suggestion to visual studio about where to
-hang the custom command.  In makefile terms this creates a new target
-in the following form:
-
-::
+This defines a command to generate specified ``OUTPUT`` file(s).
+A target created in the same directory (``CMakeLists.txt`` file)
+that specifies any output of the custom command as a source file
+is given a rule to generate the file using the command at build time.
+Do not list the output in more than one independent target that
+may build in parallel or the two instances of the rule may conflict
+(instead use the :command:`add_custom_target` command to drive the
+command and make the other targets depend on that one).
+In makefile terms this creates a new target in the following form::
 
   OUTPUT: MAIN_DEPENDENCY DEPENDS
           COMMAND
 
-If more than one command is specified they will be executed in order.
-The optional ARGS argument is for backward compatibility and will be
-ignored.
+The options are:
+
+``APPEND``
+  Append the ``COMMAND`` and ``DEPENDS`` option values to the custom
+  command for the first output specified.  There must have already
+  been a previous call to this command with the same output.
+  The ``COMMENT``, ``MAIN_DEPENDENCY``, and ``WORKING_DIRECTORY``
+  options are currently ignored when APPEND is given, but may be
+  used in the future.
+
+``COMMAND``
+  Specify the command-line(s) to execute at build time.
+  If more than one ``COMMAND`` is specified they will be executed in order,
+  but *not* necessarily composed into a stateful shell or batch script.
+  (To run a full script, use the :command:`configure_file` command or the
+  :command:`file(GENERATE)` command to create it, and then specify
+  a ``COMMAND`` to launch it.)
+  The optional ``ARGS`` argument is for backward compatibility and
+  will be ignored.
+
+  If ``COMMAND`` specifies an executable target (created by the
+  :command:`add_executable` command) it will automatically be replaced
+  by the location of the executable created at build time.
+  Additionally a target-level dependency will be added so that the
+  executable target will be built before any target using this custom
+  command.  However this does NOT add a file-level dependency that
+  would cause the custom command to re-run whenever the executable is
+  recompiled.
+
+  Arguments to ``COMMAND`` may use
+  :manual:`generator expressions <cmake-generator-expressions(7)>`.
+  References to target names in generator expressions imply target-level
+  dependencies, but NOT file-level dependencies.  List target names with
+  the ``DEPENDS`` option to add file-level dependencies.
+
+``COMMENT``
+  Display the given message before the commands are executed at
+  build time.
+
+``DEPENDS``
+  Specify files on which the command depends.  If any dependency is
+  an ``OUTPUT`` of another custom command in the same directory
+  (``CMakeLists.txt`` file) CMake automatically brings the other
+  custom command into the target in which this command is built.
+  If ``DEPENDS`` is not specified the command will run whenever
+  the ``OUTPUT`` is missing; if the command does not actually
+  create the ``OUTPUT`` then the rule will always run.
+  If ``DEPENDS`` specifies any target (created by the
+  :command:`add_custom_target`, :command:`add_executable`, or
+  :command:`add_library` command) a target-level dependency is
+  created to make sure the target is built before any target
+  using this custom command.  Additionally, if the target is an
+  executable or library a file-level dependency is created to
+  cause the custom command to re-run whenever the target is
+  recompiled.
+
+  Arguments to ``DEPENDS`` may use
+  :manual:`generator expressions <cmake-generator-expressions(7)>`.
+
+``IMPLICIT_DEPENDS``
+  Request scanning of implicit dependencies of an input file.
+  The language given specifies the programming language whose
+  corresponding dependency scanner should be used.
+  Currently only ``C`` and ``CXX`` language scanners are supported.
+  The language has to be specified for every file in the
+  ``IMPLICIT_DEPENDS`` list.  Dependencies discovered from the
+  scanning are added to those of the custom command at build time.
+  Note that the ``IMPLICIT_DEPENDS`` option is currently supported
+  only for Makefile generators and will be ignored by other generators.
+
+``MAIN_DEPENDENCY``
+  Specify the primary input source file to the command.  This is
+  treated just like any value given to the ``DEPENDS`` option
+  but also suggests to Visual Studio generators where to hang
+  the custom command.
+
+``OUTPUT``
+  Specify the output files the command is expected to produce.
+  If an output name is a relative path it will be interpreted
+  relative to the build tree directory corresponding to the
+  current source directory.
+  If the output of the custom command is not actually created
+  as a file on disk it should be marked with the :prop_sf:`SYMBOLIC`
+  source file property.
+
+``VERBATIM``
+  All arguments to the commands will be escaped properly for the
+  build tool so that the invoked command receives each argument
+  unchanged.  Note that one level of escapes is still used by the
+  CMake language processor before add_custom_command even sees the
+  arguments.  Use of ``VERBATIM`` is recommended as it enables
+  correct behavior.  When ``VERBATIM`` is not given the behavior
+  is platform specific because there is no protection of
+  tool-specific special characters.
+
+``WORKING_DIRECTORY``
+  Execute the command with the given current working directory.
+  If it is a relative path it will be interpreted relative to the
+  build tree directory corresponding to the current source directory.
+
+Build Events
+^^^^^^^^^^^^
 
 The second signature adds a custom command to a target such as a
 library or executable.  This is useful for performing an operation
@@ -60,103 +155,15 @@
 specified target.  When the command will happen is determined by which
 of the following is specified:
 
-::
-
-  PRE_BUILD - run before all other dependencies
-  PRE_LINK - run after other dependencies
-  POST_BUILD - run after the target has been built
-
-Note that the PRE_BUILD option is only supported on Visual Studio 7 or
-later.  For all other generators PRE_BUILD will be treated as
-PRE_LINK.
-
-If WORKING_DIRECTORY is specified the command will be executed in the
-directory given.  If it is a relative path it will be interpreted
-relative to the build tree directory corresponding to the current
-source directory.  If COMMENT is set, the value will be displayed as a
-message before the commands are executed at build time.  If APPEND is
-specified the COMMAND and DEPENDS option values are appended to the
-custom command for the first output specified.  There must have
-already been a previous call to this command with the same output.
-The COMMENT, WORKING_DIRECTORY, and MAIN_DEPENDENCY options are
-currently ignored when APPEND is given, but may be used in the future.
-
-If VERBATIM is given then all arguments to the commands will be
-escaped properly for the build tool so that the invoked command
-receives each argument unchanged.  Note that one level of escapes is
-still used by the CMake language processor before add_custom_command
-even sees the arguments.  Use of VERBATIM is recommended as it enables
-correct behavior.  When VERBATIM is not given the behavior is platform
-specific because there is no protection of tool-specific special
-characters.
-
-If the output of the custom command is not actually created as a file
-on disk it should be marked as SYMBOLIC with
-SET_SOURCE_FILES_PROPERTIES.
-
-The IMPLICIT_DEPENDS option requests scanning of implicit dependencies
-of an input file.  The language given specifies the programming
-language whose corresponding dependency scanner should be used.
-Currently only C and CXX language scanners are supported.  The
-language has to be specified for every file in the IMPLICIT_DEPENDS
-list.  Dependencies discovered from the scanning are added to those of
-the custom command at build time.  Note that the IMPLICIT_DEPENDS
-option is currently supported only for Makefile generators and will be
-ignored by other generators.
-
-If COMMAND specifies an executable target (created by ADD_EXECUTABLE)
-it will automatically be replaced by the location of the executable
-created at build time.  Additionally a target-level dependency will be
-added so that the executable target will be built before any target
-using this custom command.  However this does NOT add a file-level
-dependency that would cause the custom command to re-run whenever the
-executable is recompiled.
-
-Arguments to COMMAND may use "generator expressions" with the syntax
-``$<...>``.  See the :manual:`cmake-generator-expressions(7)` manual for
-available expressions.
-
-Note that tgt is not added as a dependency of the target this
-expression is evaluated on.
-
-::
-
-  $<TARGET_POLICY:pol>          = '1' if the policy was NEW when the 'head' target was created, else '0'.  If the policy was not set, the warning message for the policy will be emitted.  This generator expression only works for a subset of policies.
-  $<INSTALL_PREFIX>         = Content of the install prefix when the target is exported via INSTALL(EXPORT) and empty otherwise.
-
-Boolean expressions:
-
-::
-
-  $<AND:?[,?]...>           = '1' if all '?' are '1', else '0'
-  $<OR:?[,?]...>            = '0' if all '?' are '0', else '1'
-  $<NOT:?>                  = '0' if '?' is '1', else '1'
-
-where '?' is always either '0' or '1'.
-
-Expressions with an implicit 'this' target:
-
-::
-
-  $<TARGET_PROPERTY:prop>   = The value of the property prop on the target on which the generator expression is evaluated.
-
-References to target names in generator expressions imply target-level
-dependencies, but NOT file-level dependencies.  List target names with
-the DEPENDS option to add file dependencies.
-
-The DEPENDS option specifies files on which the command depends.  If
-any dependency is an OUTPUT of another custom command in the same
-directory (CMakeLists.txt file) CMake automatically brings the other
-custom command into the target in which this command is built.  If
-DEPENDS is not specified the command will run whenever the OUTPUT is
-missing; if the command does not actually create the OUTPUT then the
-rule will always run.  If DEPENDS specifies any target (created by an
-ADD_* command) a target-level dependency is created to make sure the
-target is built before any target using this custom command.
-Additionally, if the target is an executable or library a file-level
-dependency is created to cause the custom command to re-run whenever
-the target is recompiled.
-
-Arguments to ``DEPENDS`` may use "generator expressions" with the syntax
-``$<...>``.  See the :manual:`cmake-generator-expressions(7)` manual for
-available expressions.
+``PRE_BUILD``
+  Run before any other rules are executed within the target.
+  This is supported only on Visual Studio 7 or later.
+  For all other generators ``PRE_BUILD`` will be treated as
+  ``PRE_LINK``.
+``PRE_LINK``
+  Run after sources have been compiled but before linking the binary
+  or running the librarian or archiver tool of a static library.
+  This is not defined for targets created by the
+  :command:`add_custom_target` command.
+``POST_BUILD``
+  Run after all other rules within the target have been executed.
diff --git a/Help/command/add_library.rst b/Help/command/add_library.rst
index e93ef53..f86f3c5 100644
--- a/Help/command/add_library.rst
+++ b/Help/command/add_library.rst
@@ -1,8 +1,15 @@
 add_library
 -----------
 
+.. only:: html
+
+   .. contents::
+
 Add a library to the project using the specified source files.
 
+Normal Libraries
+^^^^^^^^^^^^^^^^
+
 ::
 
   add_library(<name> [STATIC | SHARED | MODULE]
@@ -44,7 +51,8 @@
 manual for available expressions.  See the :manual:`cmake-buildsystem(7)`
 manual for more on defining buildsystem properties.
 
---------------------------------------------------------------------------
+Imported Libraries
+^^^^^^^^^^^^^^^^^^
 
 ::
 
@@ -65,14 +73,15 @@
 location of the main library file on disk.  See documentation of the
 ``IMPORTED_*`` and ``INTERFACE_*`` properties for more information.
 
---------------------------------------------------------------------------
+Object Libraries
+^^^^^^^^^^^^^^^^
 
 ::
 
   add_library(<name> OBJECT <src>...)
 
-Creates a special "object library" target.  An object library compiles
-source files but does not archive or link their object files into a
+Creates an :ref:`Object Library <Object Libraries>`.  An object library
+compiles source files but does not archive or link their object files into a
 library.  Instead other targets created by :command:`add_library` or
 :command:`add_executable` may reference the objects using an expression of the
 form ``$<TARGET_OBJECTS:objlib>`` as a source, where ``objlib`` is the
@@ -85,7 +94,8 @@
 
 will include objlib's object files in a library and an executable
 along with those compiled from their own sources.  Object libraries
-may contain only sources (and headers) that compile to object files.
+may contain only sources that compile, header files, and other files
+that would not affect linking of a normal library (e.g. ``.txt``).
 They may contain custom commands generating such sources, but not
 ``PRE_BUILD``, ``PRE_LINK``, or ``POST_BUILD`` commands.  Object libraries
 cannot be imported, exported, installed, or linked.  Some native build
@@ -93,7 +103,8 @@
 adding at least one real source file to any target that references
 ``$<TARGET_OBJECTS:objlib>``.
 
---------------------------------------------------------------------------
+Alias Libraries
+^^^^^^^^^^^^^^^
 
 ::
 
@@ -111,7 +122,8 @@
 :command:`target_link_libraries` etc.  An ``ALIAS`` target may not be
 installed or exported.
 
---------------------------------------------------------------------------
+Interface Libraries
+^^^^^^^^^^^^^^^^^^^
 
 ::
 
@@ -124,8 +136,9 @@
 the interface target using the :command:`set_property`,
 :command:`target_link_libraries(INTERFACE)`,
 :command:`target_include_directories(INTERFACE)`,
-:command:`target_compile_options(INTERFACE)`
-and :command:`target_compile_definitions(INTERFACE)` commands, and then it
+:command:`target_compile_options(INTERFACE)`,
+:command:`target_compile_definitions(INTERFACE)`,
+and :command:`target_sources(INTERFACE)` commands, and then it
 is used as an argument to :command:`target_link_libraries` like any other
 target.
 
diff --git a/Help/command/ctest_submit.rst b/Help/command/ctest_submit.rst
index ed801bb..d9b0b78 100644
--- a/Help/command/ctest_submit.rst
+++ b/Help/command/ctest_submit.rst
@@ -5,7 +5,11 @@
 
 ::
 
-  ctest_submit([PARTS ...] [FILES ...] [RETRY_COUNT count]                [RETRY_DELAY delay][RETURN_VALUE res])
+  ctest_submit([PARTS ...] [FILES ...]
+               [RETRY_COUNT count]
+               [RETRY_DELAY delay]
+               [RETURN_VALUE res]
+               )
 
 By default all available parts are submitted if no PARTS or FILES are
 specified.  The PARTS option lists a subset of parts to be submitted.
diff --git a/Help/command/file.rst b/Help/command/file.rst
index 869350a..dbc4149 100644
--- a/Help/command/file.rst
+++ b/Help/command/file.rst
@@ -64,6 +64,9 @@
 ``REGEX <regex>``
  Consider only strings that match the given regular expression.
 
+``ENCODING <encoding-type>``
+ Consider strings of a given encoding.  "UTF-8" is currently supported.
+
 For example, the code
 
 .. code-block:: cmake
@@ -298,6 +301,7 @@
 permissions, ``PATTERN``, ``REGEX``, and ``EXCLUDE`` options.
 
 The ``INSTALL`` signature differs slightly from ``COPY``: it prints
-status messages, and ``NO_SOURCE_PERMISSIONS`` is default.
+status messages (subject to the :variable:`CMAKE_INSTALL_MESSAGE` variable),
+and ``NO_SOURCE_PERMISSIONS`` is default.
 Installation scripts generated by the :command:`install` command
 use this signature (with some undocumented options for internal use).
diff --git a/Help/command/if.rst b/Help/command/if.rst
index a45b995..79e5d21 100644
--- a/Help/command/if.rst
+++ b/Help/command/if.rst
@@ -199,3 +199,9 @@
 * The left and right hand arguments to ``AND`` and ``OR`` are independently
   tested to see if they are boolean constants, if so they are used as
   such, otherwise they are assumed to be variables and are dereferenced.
+
+To prevent ambiguity, potential variable or keyword names can be
+specified in a :ref:`Quoted Argument` or a :ref:`Bracket Argument`.
+A quoted or bracketed variable or keyword will be interpreted as a
+string and not dereferenced or interpreted.
+See policy :policy:`CMP0054`.
diff --git a/Help/command/install.rst b/Help/command/install.rst
index 47108f0..4c52abf 100644
--- a/Help/command/install.rst
+++ b/Help/command/install.rst
@@ -1,8 +1,15 @@
 install
 -------
 
+.. only:: html
+
+   .. contents::
+
 Specify rules to run at install time.
 
+Introduction
+^^^^^^^^^^^^
+
 This command generates installation rules for a project.  Rules
 specified by calls to this command within a source directory are
 executed in order during installation.  The order across directories
@@ -52,7 +59,12 @@
   Specify that it is not an error if the file to be installed does
   not exist.
 
-------------------------------------------------------------------------------
+Command signatures that install files may print messages during
+installation.  Use the :variable:`CMAKE_INSTALL_MESSAGE` variable
+to control which messages are printed.
+
+Installing Targets
+^^^^^^^^^^^^^^^^^^
 
 ::
 
@@ -147,7 +159,8 @@
 Installing a target with the :prop_tgt:`EXCLUDE_FROM_ALL` target property
 set to ``TRUE`` has undefined behavior.
 
-------------------------------------------------------------------------------
+Installing Files
+^^^^^^^^^^^^^^^^
 
 ::
 
@@ -175,14 +188,15 @@
 However, if any item begins in a generator expression it must evaluate
 to a full path.
 
-------------------------------------------------------------------------------
+Installing Directories
+^^^^^^^^^^^^^^^^^^^^^^
 
 ::
 
   install(DIRECTORY dirs... DESTINATION <dir>
           [FILE_PERMISSIONS permissions...]
           [DIRECTORY_PERMISSIONS permissions...]
-          [USE_SOURCE_PERMISSIONS] [OPTIONAL]
+          [USE_SOURCE_PERMISSIONS] [OPTIONAL] [MESSAGE_NEVER]
           [CONFIGURATIONS [Debug|Release|...]]
           [COMPONENT <component>] [FILES_MATCHING]
           [[PATTERN <pattern> | REGEX <regex>]
@@ -205,6 +219,8 @@
 directories will be given the default permissions specified in the
 ``PROGRAMS`` form of the command.
 
+The ``MESSAGE_NEVER`` option disables file installation status output.
+
 Installation of directories may be controlled with fine granularity
 using the ``PATTERN`` or ``REGEX`` options.  These "match" options specify a
 globbing pattern or regular expression to match directories or files
@@ -247,7 +263,8 @@
 file permissions, the scripts will be given specific permissions, and any
 ``CVS`` directories will be excluded.
 
-------------------------------------------------------------------------------
+Custom Installation Logic
+^^^^^^^^^^^^^^^^^^^^^^^^^
 
 ::
 
@@ -266,7 +283,8 @@
 
 will print a message during installation.
 
-------------------------------------------------------------------------------
+Installing Exports
+^^^^^^^^^^^^^^^^^^
 
 ::
 
diff --git a/Help/command/set_tests_properties.rst b/Help/command/set_tests_properties.rst
index 82cd5d8..e29d690 100644
--- a/Help/command/set_tests_properties.rst
+++ b/Help/command/set_tests_properties.rst
@@ -27,7 +27,7 @@
 
 ::
 
-  Example: PASS_REGULAR_EXPRESSION "[^a-z]Error;ERROR;Failed"
+  Example: FAIL_REGULAR_EXPRESSION "[^a-z]Error;ERROR;Failed"
 
 Both PASS_REGULAR_EXPRESSION and FAIL_REGULAR_EXPRESSION expect a list
 of regular expressions.
diff --git a/Help/command/string.rst b/Help/command/string.rst
index abde6ee..07d0ff3 100644
--- a/Help/command/string.rst
+++ b/Help/command/string.rst
@@ -36,6 +36,8 @@
   string(TIMESTAMP <output variable> [<format string>] [UTC])
   string(MAKE_C_IDENTIFIER <input string> <output variable>)
   string(GENEX_STRIP <input string> <output variable>)
+  string(UUID <output variable> NAMESPACE <namespace> NAME <name>
+         TYPE <MD5|SHA1> [UPPER])
 
 REGEX MATCH will match the regular expression once and store the match
 in the output variable.
@@ -159,3 +161,13 @@
 ``GENEX_STRIP`` will strip any
 :manual:`generator expressions <cmake-generator-expressions(7)>` from the
 ``input string`` and store the result in the ``output variable``.
+
+UUID creates a univerally unique identifier (aka GUID) as per RFC4122
+based on the hash of the combined values of <namespace>
+(which itself has to be a valid UUID) and <name>.
+The hash algorithm can be either ``MD5`` (Version 3 UUID) or
+``SHA1`` (Version 5 UUID).
+A UUID has the format ``xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx``
+where each `x` represents a lower case hexadecimal character.
+Where required an uppercase representation can be requested
+with the optional ``UPPER`` flag.
diff --git a/Help/command/target_link_libraries.rst b/Help/command/target_link_libraries.rst
index bced169..39537a7 100644
--- a/Help/command/target_link_libraries.rst
+++ b/Help/command/target_link_libraries.rst
@@ -18,7 +18,10 @@
 dependency will automatically be added in the build system to make sure
 the library being linked is up-to-date before the target links. Item names
 starting with ``-``, but not ``-l`` or ``-framework``, are treated as
-linker flags.
+linker flags.  Note that such flags will be treated like any other library
+link item for purposes of transitive dependencies, so they are generally
+safe to specify only as private link items that will not propagate to
+dependents of ``<target>``.
 
 A ``debug``, ``optimized``, or ``general`` keyword indicates that the
 library immediately following it is to be used only for the
diff --git a/Help/command/try_compile.rst b/Help/command/try_compile.rst
index 8ed3cf4..224c67b 100644
--- a/Help/command/try_compile.rst
+++ b/Help/command/try_compile.rst
@@ -36,9 +36,10 @@
 passed to cmake to avoid this clean.  However, multiple sequential
 try_compile operations reuse this single output directory.  If you use
 --debug-trycompile, you can only debug one try_compile call at a time.
-The recommended procedure is to configure with cmake all the way
-through once, then delete the cache entry associated with the
-try_compile call of interest, and then re-run cmake again with
+The recommended procedure is to protect all try_compile calls in your
+project by ``if(NOT DEFINED RESULT_VAR)`` logic, configure with cmake
+all the way through once, then delete the cache entry associated with
+the try_compile call of interest, and then re-run cmake again with
 --debug-trycompile.
 
 Some extra flags that can be included are, INCLUDE_DIRECTORIES,
diff --git a/Help/generator/Visual Studio 10 2010.rst b/Help/generator/Visual Studio 10 2010.rst
index 000677a..77ea9df 100644
--- a/Help/generator/Visual Studio 10 2010.rst
+++ b/Help/generator/Visual Studio 10 2010.rst
@@ -3,10 +3,17 @@
 
 Generates Visual Studio 10 (VS 2010) project files.
 
-It is possible to append a space followed by the platform name to
-create project files for a specific target platform.  E.g.
-"Visual Studio 10 2010 Win64" will create project files for the
-x64 processor; "Visual Studio 10 2010 IA64" for Itanium.
+The :variable:`CMAKE_GENERATOR_PLATFORM` variable may be set
+to specify a target platform name.
+
+For compatibility with CMake versions prior to 3.1, one may specify
+a target platform name optionally at the end of this generator name:
+
+``Visual Studio 10 2010 Win64``
+  Specify target platform ``x64``.
+
+``Visual Studio 10 2010 IA64``
+  Specify target platform ``Itanium``.
 
 For compatibility with CMake versions prior to 3.0, one may specify this
-generator using the name "Visual Studio 10" without the year component.
+generator using the name ``Visual Studio 10`` without the year component.
diff --git a/Help/generator/Visual Studio 11 2012.rst b/Help/generator/Visual Studio 11 2012.rst
index 42f6f91..5fa7f2c 100644
--- a/Help/generator/Visual Studio 11 2012.rst
+++ b/Help/generator/Visual Studio 11 2012.rst
@@ -3,10 +3,20 @@
 
 Generates Visual Studio 11 (VS 2012) project files.
 
-It is possible to append a space followed by the platform name to
-create project files for a specific target platform.  E.g.
-"Visual Studio 11 2012 Win64" will create project files for the
-x64 processor; "Visual Studio 11 2012 ARM" for ARM.
+The :variable:`CMAKE_GENERATOR_PLATFORM` variable may be set
+to specify a target platform name.
+
+For compatibility with CMake versions prior to 3.1, one may specify
+a target platform name optionally at the end of this generator name:
+
+``Visual Studio 11 2012 Win64``
+  Specify target platform ``x64``.
+
+``Visual Studio 11 2012 ARM``
+  Specify target platform ``ARM``.
+
+``Visual Studio 11 2012 <WinCE-SDK>``
+  Specify target platform matching a Windows CE SDK name.
 
 For compatibility with CMake versions prior to 3.0, one may specify this
 generator using the name "Visual Studio 11" without the year component.
diff --git a/Help/generator/Visual Studio 12 2013.rst b/Help/generator/Visual Studio 12 2013.rst
index d2f4912..2c3b119 100644
--- a/Help/generator/Visual Studio 12 2013.rst
+++ b/Help/generator/Visual Studio 12 2013.rst
@@ -3,10 +3,17 @@
 
 Generates Visual Studio 12 (VS 2013) project files.
 
-It is possible to append a space followed by the platform name to
-create project files for a specific target platform.  E.g.
-"Visual Studio 12 2013 Win64" will create project files for the
-x64 processor; "Visual Studio 12 2013 ARM" for ARM.
+The :variable:`CMAKE_GENERATOR_PLATFORM` variable may be set
+to specify a target platform name.
+
+For compatibility with CMake versions prior to 3.1, one may specify
+a target platform name optionally at the end of this generator name:
+
+``Visual Studio 12 2013 Win64``
+  Specify target platform ``x64``.
+
+``Visual Studio 12 2013 ARM``
+  Specify target platform ``ARM``.
 
 For compatibility with CMake versions prior to 3.0, one may specify this
 generator using the name "Visual Studio 12" without the year component.
diff --git a/Help/generator/Visual Studio 14.rst b/Help/generator/Visual Studio 14.rst
new file mode 100644
index 0000000..d621b7e
--- /dev/null
+++ b/Help/generator/Visual Studio 14.rst
@@ -0,0 +1,16 @@
+Visual Studio 14
+----------------
+
+Generates Visual Studio 14 project files.
+
+The :variable:`CMAKE_GENERATOR_PLATFORM` variable may be set
+to specify a target platform name.
+
+For compatibility with CMake versions prior to 3.1, one may specify
+a target platform name optionally at the end of this generator name:
+
+``Visual Studio 14 Win64``
+  Specify target platform ``x64``.
+
+``Visual Studio 14 ARM``
+  Specify target platform ``ARM``.
diff --git a/Help/generator/Visual Studio 8 2005.rst b/Help/generator/Visual Studio 8 2005.rst
index d7b6de2..29012c3 100644
--- a/Help/generator/Visual Studio 8 2005.rst
+++ b/Help/generator/Visual Studio 8 2005.rst
@@ -3,6 +3,14 @@
 
 Generates Visual Studio 8 2005 project files.
 
-It is possible to append a space followed by the platform name to
-create project files for a specific target platform.  E.g.  "Visual
-Studio 8 2005 Win64" will create project files for the x64 processor.
+The :variable:`CMAKE_GENERATOR_PLATFORM` variable may be set
+to specify a target platform name.
+
+For compatibility with CMake versions prior to 3.1, one may specify
+a target platform name optionally at the end of this generator name:
+
+``Visual Studio 8 2005 Win64``
+  Specify target platform ``x64``.
+
+``Visual Studio 8 2005 <WinCE-SDK>``
+  Specify target platform matching a Windows CE SDK name.
diff --git a/Help/generator/Visual Studio 9 2008.rst b/Help/generator/Visual Studio 9 2008.rst
index ade9fd5..40471b9 100644
--- a/Help/generator/Visual Studio 9 2008.rst
+++ b/Help/generator/Visual Studio 9 2008.rst
@@ -3,7 +3,17 @@
 
 Generates Visual Studio 9 2008 project files.
 
-It is possible to append a space followed by the platform name to
-create project files for a specific target platform.  E.g.  "Visual
-Studio 9 2008 Win64" will create project files for the x64 processor;
-"Visual Studio 9 2008 IA64" for Itanium.
+The :variable:`CMAKE_GENERATOR_PLATFORM` variable may be set
+to specify a target platform name.
+
+For compatibility with CMake versions prior to 3.1, one may specify
+a target platform name optionally at the end of this generator name:
+
+``Visual Studio 9 2008 Win64``
+  Specify target platform ``x64``.
+
+``Visual Studio 9 2008 IA64``
+  Specify target platform ``Itanium``.
+
+``Visual Studio 9 2008 <WinCE-SDK>``
+  Specify target platform matching a Windows CE SDK name.
diff --git a/Help/manual/OPTIONS_BUILD.txt b/Help/manual/OPTIONS_BUILD.txt
index 2079c44..363d0aa 100644
--- a/Help/manual/OPTIONS_BUILD.txt
+++ b/Help/manual/OPTIONS_BUILD.txt
@@ -51,6 +51,17 @@
 
  See native build system documentation for allowed toolset names.
 
+``-A <platform-name>``
+ Specify platform name if supported by generator.
+
+ Some CMake generators support a platform name to be given to the
+ native build system to choose a compiler or SDK.  This is supported only on
+ specific generators::
+
+   Visual Studio >= 8
+
+ See native build system documentation for allowed platform names.
+
 ``-Wno-dev``
  Suppress developer warnings.
 
diff --git a/Help/manual/cmake-buildsystem.7.rst b/Help/manual/cmake-buildsystem.7.rst
index fdd1be4..1ce9a7e 100644
--- a/Help/manual/cmake-buildsystem.7.rst
+++ b/Help/manual/cmake-buildsystem.7.rst
@@ -19,8 +19,8 @@
 Binary Targets
 ==============
 
-Executables and libraries are defined using the :command:`add_library`
-and :command:`add_executable` commands.  The resulting binary files have
+Executables and libraries are defined using the :command:`add_executable`
+and :command:`add_library` commands.  The resulting binary files have
 appropriate prefixes, suffixes and extensions for the platform targeted.
 Dependencies between binary targets are expressed using the
 :command:`target_link_libraries` command:
@@ -37,9 +37,28 @@
 When linking the ``zipapp`` executable, the ``archive`` static library is
 linked in.
 
+Binary Executables
+------------------
+
+The :command:`add_executable` command defines an executable target:
+
+.. code-block:: cmake
+
+  add_executable(mytool mytool.cpp)
+
+Commands such as :command:`add_custom_command`, which generates rules to be
+run at build time can transparently use an :prop_tgt:`EXECUTABLE <TYPE>`
+target as a ``COMMAND`` executable.  The buildsystem rules will ensure that
+the executable is built before attempting to run the command.
+
 Binary Library Types
 --------------------
 
+.. _`Normal Libraries`:
+
+Normal Libraries
+^^^^^^^^^^^^^^^^
+
 By default, the :command:`add_library` command defines a static library,
 unless a type is specified.  A type may be specified when using the command:
 
@@ -66,6 +85,11 @@
 
   add_library(archive MODULE 7z.cpp)
 
+.. _`Object Libraries`:
+
+Object Libraries
+^^^^^^^^^^^^^^^^
+
 The ``OBJECT`` library type is also not linked to. It defines a non-archival
 collection of object files resulting from compiling the given source files.
 The object files collection can be used as source inputs to other targets:
@@ -83,10 +107,11 @@
 :command:`target_link_libraries`.  They also may not be used as the ``TARGET``
 in a use of the :command:`add_custom_command(TARGET)` command signature.
 
-Commands such as :command:`add_custom_command`, which generates rules to be
-run at build time can transparently use an :prop_tgt:`EXECUTABLE <TYPE>`
-target as a ``COMMAND`` executable.  The buildsystem rules will ensure that
-the executable is built before attempting to run the command.
+Although object libraries may not be named directly in calls to
+the :command:`target_link_libraries` command, they can be "linked"
+indirectly by using an :ref:`Interface Library <Interface Libraries>`
+whose :prop_tgt:`INTERFACE_SOURCES` target property is set to name
+``$<TARGET_OBJECTS:objlib>``.
 
 Build Specification and Usage Requirements
 ==========================================
@@ -786,11 +811,12 @@
 :prop_tgt:`INTERFACE_COMPILE_DEFINITIONS`,
 :prop_tgt:`INTERFACE_COMPILE_OPTIONS`,
 :prop_tgt:`INTERFACE_LINK_LIBRARIES`, and
+:prop_tgt:`INTERFACE_SOURCES`,
 :prop_tgt:`INTERFACE_POSITION_INDEPENDENT_CODE`.
 Only the ``INTERFACE`` modes of the :command:`target_include_directories`,
 :command:`target_compile_definitions`, :command:`target_compile_options`,
-and :command:`target_link_libraries` commands may be used with ``INTERFACE``
-libraries.
+:command:`target_sources`, and :command:`target_link_libraries` commands
+may be used with ``INTERFACE`` libraries.
 
 A primary use-case for ``INTERFACE`` libraries is header-only libraries.
 
diff --git a/Help/manual/cmake-compile-features.7.rst b/Help/manual/cmake-compile-features.7.rst
index d4bbecc..8e3dbb8 100644
--- a/Help/manual/cmake-compile-features.7.rst
+++ b/Help/manual/cmake-compile-features.7.rst
@@ -166,11 +166,11 @@
     virtual void Execute() = 0;
   };
 
-  struct Concrete Foo_CXX_FINAL {
-    void Execute() Foo_CXX_OVERRIDE;
+  struct Concrete Foo_FINAL {
+    void Execute() Foo_OVERRIDE;
   };
 
-In this case, ``Foo_CXX_FINAL`` will expand to ``final`` if the
+In this case, ``Foo_FINAL`` will expand to ``final`` if the
 compiler supports the keyword, or to empty otherwise.
 
 In this use-case, the CMake code will wish to enable a particular language
@@ -189,13 +189,13 @@
       cxx_final cxx_override
   )
 
-  # Includes foo_compiler_detection.h and uses the Foo_DECL_CXX_FINAL symbol
+  # Includes foo_compiler_detection.h and uses the Foo_FINAL symbol
   # which will expand to 'final' if the compiler supports the requested
   # CXX_STANDARD.
   add_library(foo foo.cpp)
   set_property(TARGET foo PROPERTY CXX_STANDARD 11)
 
-  # Includes foo_compiler_detection.h and uses the Foo_DECL_CXX_FINAL symbol
+  # Includes foo_compiler_detection.h and uses the Foo_FINAL symbol
   # which will expand to 'final' if the compiler supports the feature,
   # even though CXX_STANDARD is not set explicitly.  The requirement of
   # cxx_constexpr causes CMake to set CXX_STANDARD internally, which
@@ -276,10 +276,13 @@
 .. code-block:: cmake
 
   add_library(foo INTERFACE)
+  set(with_variadics ${CMAKE_CURRENT_SOURCE_DIR}/with_variadics)
+  set(no_variadics ${CMAKE_CURRENT_SOURCE_DIR}/no_variadics)
   target_link_libraries(foo
     INTERFACE
-      "$<$<COMPILE_FEATURES:cxx_variadic_templates>:${CMAKE_CURRENT_SOURCE_DIR}/with_variadics>"
-      "$<$<NOT:$<COMPILE_FEATURES:cxx_variadic_templates>>:${CMAKE_CURRENT_SOURCE_DIR}/no_variadics>")
+      "$<$<COMPILE_FEATURES:cxx_variadic_templates>:${with_variadics}>"
+      "$<$<NOT:$<COMPILE_FEATURES:cxx_variadic_templates>>:${no_variadics}>"
+    )
 
 Consuming code then simply links to the ``foo`` target as usual and uses
 the feature-appropriate include directory
diff --git a/Help/manual/cmake-developer.7.rst b/Help/manual/cmake-developer.7.rst
index 9851c12..eea5fc3 100644
--- a/Help/manual/cmake-developer.7.rst
+++ b/Help/manual/cmake-developer.7.rst
@@ -188,8 +188,8 @@
 
 Various implementations have differing implementation of ``size_t``.  When
 assigning the result of ``.size()`` on a container for example, the result
-should not be assigned to an ``unsigned int`` or similar. ``std::size_t`` must
-not be used.
+should be assigned to ``size_t`` not to ``std::size_t``, ``unsigned int`` or
+similar types.
 
 Templates
 ---------
@@ -521,14 +521,15 @@
 Command signatures should be marked up as plain literal blocks, not as
 cmake ``code-blocks``.
 
-Signatures are separated from preceding content by a horizontal
-line. That is, use:
+Signatures are separated from preceding content by a section header.
+That is, use:
 
 .. code-block:: rst
 
   ... preceding paragraph.
 
-  ---------------------------------------------------------------------
+  Normal Libraries
+  ^^^^^^^^^^^^^^^^
 
   ::
 
@@ -1004,7 +1005,8 @@
 .. code-block:: cmake
 
   if(CMAKE_MINIMUM_REQUIRED_VERSION VERSION_LESS 3.0.0)
-    message(AUTHOR_WARNING "Your project should require at least CMake 3.0.0 to use FindFoo.cmake")
+    message(AUTHOR_WARNING
+      "Your project should require at least CMake 3.0.0 to use FindFoo.cmake")
   endif()
 
 Now the actual libraries and so on have to be found.  The code here will
diff --git a/Help/manual/cmake-generator-expressions.7.rst b/Help/manual/cmake-generator-expressions.7.rst
index f04702e..981bd84 100644
--- a/Help/manual/cmake-generator-expressions.7.rst
+++ b/Help/manual/cmake-generator-expressions.7.rst
@@ -38,6 +38,8 @@
 expands to ``DEBUG_MODE`` when the ``Debug`` configuration is used, and
 otherwise expands to nothing.
 
+Available logical expressions are:
+
 ``$<0:...>``
   Empty string (ignores ``...``)
 ``$<1:...>``
@@ -111,20 +113,27 @@
 :variable:`CMAKE_CXX_COMPILER_VERSION <CMAKE_<LANG>_COMPILER_VERSION>` is less
 than 4.2.0.
 
+Available informational expressions are:
+
 ``$<CONFIGURATION>``
   Configuration name. Deprecated. Use ``CONFIG`` instead.
 ``$<CONFIG>``
   Configuration name
 ``$<PLATFORM_ID>``
-  The CMake-id of the platform
+  The CMake-id of the platform.
+  See also the :variable:`CMAKE_SYSTEM_NAME` variable.
 ``$<C_COMPILER_ID>``
   The CMake-id of the C compiler used.
+  See also the :variable:`CMAKE_<LANG>_COMPILER_ID` variable.
 ``$<CXX_COMPILER_ID>``
   The CMake-id of the CXX compiler used.
+  See also the :variable:`CMAKE_<LANG>_COMPILER_ID` variable.
 ``$<C_COMPILER_VERSION>``
   The version of the C compiler used.
+  See also the :variable:`CMAKE_<LANG>_COMPILER_VERSION` variable.
 ``$<CXX_COMPILER_VERSION>``
   The version of the CXX compiler used.
+  See also the :variable:`CMAKE_<LANG>_COMPILER_VERSION` variable.
 ``$<TARGET_FILE:tgt>``
   Full path to main file (.exe, .so.1.2, .a) where ``tgt`` is the name of a target.
 ``$<TARGET_FILE_NAME:tgt>``
@@ -143,6 +152,17 @@
   Name of file with soname (.so.3).
 ``$<TARGET_SONAME_FILE_DIR:tgt>``
   Directory of with soname (.so.3).
+``$<TARGET_PDB_FILE:tgt>``
+  Full path to the linker generated program database file (.pdb)
+  where ``tgt`` is the name of a target.
+
+  See also the :prop_tgt:`PDB_NAME` and :prop_tgt:`PDB_OUTPUT_DIRECTORY`
+  target properties and their configuration specific variants
+  :prop_tgt:`PDB_NAME_<CONFIG>` and :prop_tgt:`PDB_OUTPUT_DIRECTORY_<CONFIG>`.
+``$<TARGET_PDB_FILE_NAME:tgt>``
+  Name of the linker generated program database file (.pdb).
+``$<TARGET_PDB_FILE_DIR:tgt>``
+  Directory of the linker generated program database file (.pdb).
 ``$<TARGET_PROPERTY:tgt,prop>``
   Value of the property ``prop`` on the target ``tgt``.
 
@@ -169,7 +189,13 @@
 in this situation would require first checking if the INCLUDE_DIRECTORIES
 property is non-empty::
 
-  $<$<BOOL:$<TARGET_PROPERTY:INCLUDE_DIRECTORIES>>:-I$<JOIN:$<TARGET_PROPERTY:INCLUDE_DIRECTORIES>, -I>>
+  $<$<BOOL:${prop}>:-I$<JOIN:${prop}, -I>>
+
+where ``${prop}`` refers to a helper variable::
+
+  set(prop "$<TARGET_PROPERTY:INCLUDE_DIRECTORIES>")
+
+Available output expressions are:
 
 ``$<JOIN:list,...>``
   Joins the list with the content of ``...``
@@ -183,6 +209,13 @@
   Marks ``...`` as being the name of a target.  This is required if exporting
   targets to multiple dependent export sets.  The ``...`` must be a literal
   name of a target- it may not contain generator expressions.
+``$<LINK_ONLY:...>``
+  Content of ``...`` except when evaluated in a link interface while
+  propagating :ref:`Target Usage Requirements`, in which case it is the
+  empty string.
+  Intended for use only in an :prop_tgt:`INTERFACE_LINK_LIBRARIES` target
+  property, perhaps via the :command:`target_link_libraries` command,
+  to specify private link dependencies without other usage requirements.
 ``$<INSTALL_INTERFACE:...>``
   Content of ``...`` when the property is exported using :command:`install(EXPORT)`,
   and empty otherwise.
diff --git a/Help/manual/cmake-generators.7.rst b/Help/manual/cmake-generators.7.rst
index 8d0c704..7f5093f 100644
--- a/Help/manual/cmake-generators.7.rst
+++ b/Help/manual/cmake-generators.7.rst
@@ -64,6 +64,7 @@
    /generator/Visual Studio 10 2010
    /generator/Visual Studio 11 2012
    /generator/Visual Studio 12 2013
+   /generator/Visual Studio 14
    /generator/Xcode
 
 Extra Generators
diff --git a/Help/manual/cmake-modules.7.rst b/Help/manual/cmake-modules.7.rst
index ecc9cc4..61e4bb4 100644
--- a/Help/manual/cmake-modules.7.rst
+++ b/Help/manual/cmake-modules.7.rst
@@ -23,6 +23,7 @@
    /module/CheckCXXSourceRuns
    /module/CheckCXXSymbolExists
    /module/CheckFortranFunctionExists
+   /module/CheckFortranSourceCompiles
    /module/CheckFunctionExists
    /module/CheckIncludeFileCXX
    /module/CheckIncludeFile
@@ -55,6 +56,7 @@
    /module/CPackCygwin
    /module/CPackDeb
    /module/CPackDMG
+   /module/CPackIFW
    /module/CPackNSIS
    /module/CPackPackageMaker
    /module/CPackRPM
@@ -113,6 +115,7 @@
    /module/FindHg
    /module/FindHSPELL
    /module/FindHTMLHelp
+   /module/FindIce
    /module/FindIcotool
    /module/FindImageMagick
    /module/FindITK
@@ -205,6 +208,7 @@
    /module/FindWish
    /module/FindwxWidgets
    /module/FindwxWindows
+   /module/FindXerces
    /module/FindX11
    /module/FindXMLRPC
    /module/FindZLIB
diff --git a/Help/manual/cmake-policies.7.rst b/Help/manual/cmake-policies.7.rst
index 136cf5c..f1717a0 100644
--- a/Help/manual/cmake-policies.7.rst
+++ b/Help/manual/cmake-policies.7.rst
@@ -105,3 +105,4 @@
    /policy/CMP0051
    /policy/CMP0052
    /policy/CMP0053
+   /policy/CMP0054
diff --git a/Help/manual/cmake-properties.7.rst b/Help/manual/cmake-properties.7.rst
index e4546c1..38bcd04 100644
--- a/Help/manual/cmake-properties.7.rst
+++ b/Help/manual/cmake-properties.7.rst
@@ -51,7 +51,6 @@
    /prop_dir/CACHE_VARIABLES
    /prop_dir/CLEAN_NO_CUSTOM
    /prop_dir/CMAKE_CONFIGURE_DEPENDS
-   /prop_dir/COMPILE_DEFINITIONS_CONFIG
    /prop_dir/COMPILE_DEFINITIONS
    /prop_dir/COMPILE_OPTIONS
    /prop_dir/DEFINITIONS
@@ -80,6 +79,8 @@
    :maxdepth: 1
 
    /prop_tgt/ALIASED_TARGET
+   /prop_tgt/ANDROID_API
+   /prop_tgt/ANDROID_GUI
    /prop_tgt/ARCHIVE_OUTPUT_DIRECTORY_CONFIG
    /prop_tgt/ARCHIVE_OUTPUT_DIRECTORY
    /prop_tgt/ARCHIVE_OUTPUT_NAME_CONFIG
@@ -101,7 +102,6 @@
    /prop_tgt/COMPATIBLE_INTERFACE_NUMBER_MAX
    /prop_tgt/COMPATIBLE_INTERFACE_NUMBER_MIN
    /prop_tgt/COMPATIBLE_INTERFACE_STRING
-   /prop_tgt/COMPILE_DEFINITIONS_CONFIG
    /prop_tgt/COMPILE_DEFINITIONS
    /prop_tgt/COMPILE_FEATURES
    /prop_tgt/COMPILE_FLAGS
@@ -205,9 +205,7 @@
    /prop_tgt/PDB_OUTPUT_DIRECTORY_CONFIG
    /prop_tgt/PDB_OUTPUT_DIRECTORY
    /prop_tgt/POSITION_INDEPENDENT_CODE
-   /prop_tgt/POST_INSTALL_SCRIPT
    /prop_tgt/PREFIX
-   /prop_tgt/PRE_INSTALL_SCRIPT
    /prop_tgt/PRIVATE_HEADER
    /prop_tgt/PROJECT_LABEL
    /prop_tgt/PUBLIC_HEADER
@@ -239,6 +237,7 @@
    /prop_tgt/VS_SCC_LOCALPATH
    /prop_tgt/VS_SCC_PROJECTNAME
    /prop_tgt/VS_SCC_PROVIDER
+   /prop_tgt/VS_WINRT_COMPONENT
    /prop_tgt/VS_WINRT_EXTENSIONS
    /prop_tgt/VS_WINRT_REFERENCES
    /prop_tgt/WIN32_EXECUTABLE
@@ -277,7 +276,6 @@
    /prop_sf/ABSTRACT
    /prop_sf/AUTOUIC_OPTIONS
    /prop_sf/AUTORCC_OPTIONS
-   /prop_sf/COMPILE_DEFINITIONS_CONFIG
    /prop_sf/COMPILE_DEFINITIONS
    /prop_sf/COMPILE_FLAGS
    /prop_sf/EXTERNAL_OBJECT
@@ -292,6 +290,8 @@
    /prop_sf/OBJECT_DEPENDS
    /prop_sf/OBJECT_OUTPUTS
    /prop_sf/SYMBOLIC
+   /prop_sf/VS_DEPLOYMENT_CONTENT
+   /prop_sf/VS_SHADER_TYPE
    /prop_sf/WRAP_EXCLUDE
    /prop_sf/XCODE_EXPLICIT_FILE_TYPE
    /prop_sf/XCODE_LAST_KNOWN_FILE_TYPE
@@ -317,3 +317,33 @@
 
    /prop_inst/CPACK_NEVER_OVERWRITE.rst
    /prop_inst/CPACK_PERMANENT.rst
+   /prop_inst/CPACK_WIX_ACL.rst
+
+
+Deprecated Properties on Directories
+=====================================
+
+.. toctree::
+   :maxdepth: 1
+
+   /prop_dir/COMPILE_DEFINITIONS_CONFIG
+
+
+Deprecated Properties on Targets
+================================
+
+.. toctree::
+   :maxdepth: 1
+
+   /prop_tgt/COMPILE_DEFINITIONS_CONFIG
+   /prop_tgt/POST_INSTALL_SCRIPT
+   /prop_tgt/PRE_INSTALL_SCRIPT
+
+
+Deprecated Properties on Source Files
+=====================================
+
+.. toctree::
+   :maxdepth: 1
+
+   /prop_sf/COMPILE_DEFINITIONS_CONFIG
diff --git a/Help/manual/cmake-toolchains.7.rst b/Help/manual/cmake-toolchains.7.rst
index f36a43c..fad5481 100644
--- a/Help/manual/cmake-toolchains.7.rst
+++ b/Help/manual/cmake-toolchains.7.rst
@@ -97,18 +97,27 @@
 
 If :manual:`cmake(1)` is invoked with the command line parameter
 ``-DCMAKE_TOOLCHAIN_FILE=path/to/file``, the file will be loaded early to set
-values for the compilers. A typical cross-compiling toolchain has content such
+values for the compilers.
+The :variable:`CMAKE_CROSSCOMPILING` variable is set to true when CMake is
+cross-compiling.
+
+Cross Compiling for Linux
+-------------------------
+
+A typical cross-compiling toolchain for Linux has content such
 as:
 
 .. code-block:: cmake
 
   set(CMAKE_SYSTEM_NAME Linux)
+  set(CMAKE_SYSTEM_PROCESSOR arm)
 
   set(CMAKE_SYSROOT /home/devel/rasp-pi-rootfs)
   set(CMAKE_STAGING_PREFIX /home/devel/stage)
 
-  set(CMAKE_C_COMPILER /home/devel/gcc-4.7-linaro-rpi-gnueabihf/bin/arm-linux-gnueabihf-gcc)
-  set(CMAKE_CXX_COMPILER /home/devel/gcc-4.7-linaro-rpi-gnueabihf/bin/arm-linux-gnueabihf-g++)
+  set(tools /home/devel/gcc-4.7-linaro-rpi-gnueabihf)
+  set(CMAKE_C_COMPILER ${tools}/bin/arm-linux-gnueabihf-gcc)
+  set(CMAKE_CXX_COMPILER ${tools}/bin/arm-linux-gnueabihf-g++)
 
   set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
   set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
@@ -118,6 +127,9 @@
 The :variable:`CMAKE_SYSTEM_NAME` is the CMake-identifier of the target platform
 to build for.
 
+The :variable:`CMAKE_SYSTEM_PROCESSOR` is the CMake-identifier of the target architecture
+to build for.
+
 The :variable:`CMAKE_SYSROOT` is optional, and may be specified if a sysroot
 is available.
 
@@ -139,13 +151,17 @@
 should be found only on the host and not on the target. This is the purpose of
 the ``CMAKE_FIND_ROOT_PATH_MODE_*`` variables.
 
-Some compilers are inherently cross compilers, such as Clang and the QNX QCC
-compiler. The :variable:`CMAKE_<LANG>_COMPILER_TARGET` can be set to pass a
+Cross Compiling using Clang
+---------------------------
+
+Some compilers such as Clang are inherently cross compilers.
+The :variable:`CMAKE_<LANG>_COMPILER_TARGET` can be set to pass a
 value to those supported compilers when compiling:
 
 .. code-block:: cmake
 
   set(CMAKE_SYSTEM_NAME Linux)
+  set(CMAKE_SYSTEM_PROCESSOR arm)
 
   set(triple arm-linux-gnueabihf)
 
@@ -154,7 +170,18 @@
   set(CMAKE_CXX_COMPILER clang++)
   set(CMAKE_CXX_COMPILER_TARGET ${triple})
 
-Or, for QCC:
+Similarly, some compilers do not ship their own supplementary utilities
+such as linkers, but provide a way to specify the location of the external
+toolchain which will be used by the compiler driver. The
+:variable:`CMAKE_<LANG>_COMPILER_EXTERNAL_TOOLCHAIN` variable can be set in a
+toolchain file to pass the path to the compiler driver.
+
+Cross Compiling for QNX
+-----------------------
+
+As the Clang compiler the QNX QCC compile is inherently a cross compiler.
+And the :variable:`CMAKE_<LANG>_COMPILER_TARGET` can be set to pass a
+value to those supported compilers when compiling:
 
 .. code-block:: cmake
 
@@ -167,12 +194,50 @@
   set(CMAKE_CXX_COMPILER QCC)
   set(CMAKE_CXX_COMPILER_TARGET ${arch})
 
+Cross Compiling for Windows CE
+------------------------------
 
-Similarly, some compilers do not ship their own supplementary utilities
-such as linkers, but provide a way to specify the location of the external
-toolchain which will be used by the compiler driver. The
-:variable:`CMAKE_<LANG>_COMPILER_EXTERNAL_TOOLCHAIN` variable can be set in a
-toolchain file to pass the path to the compiler driver.
+Cross compiling for Windows CE requires the corresponding SDK being
+installed on your system.  These SDKs are usually installed under
+``C:/Program Files (x86)/Windows CE Tools/SDKs``.
 
-The :variable:`CMAKE_CROSSCOMPILING` variable is set to true when CMake is
-cross-compiling.
+A toolchain file to configure a Visual Studio generator for
+Windows CE may look like this:
+
+.. code-block:: cmake
+
+  set(CMAKE_SYSTEM_NAME WindowsCE)
+
+  set(CMAKE_SYSTEM_VERSION 8.0)
+  set(CMAKE_SYSTEM_PROCESSOR arm)
+
+  set(CMAKE_GENERATOR_TOOLSET CE800) # Can be omitted for 8.0
+  set(CMAKE_GENERATOR_PLATFORM SDK_AM335X_SK_WEC2013_V310)
+
+The :variable:`CMAKE_GENERATOR_PLATFORM` tells the generator which SDK to use.
+Further :variable:`CMAKE_SYSTEM_VERSION` tells the generator what version of
+Windows CE to use.  Currently version 8.0 (Windows Embedded Compact 2013) is
+supported out of the box.  Other versions may require one to set
+:variable:`CMAKE_GENERATOR_TOOLSET` to the correct value.
+
+Cross Compiling for Windows Phone
+---------------------------------
+
+A toolchain file to configure a Visual Studio generator for
+Windows Phone may look like this:
+
+.. code-block:: cmake
+
+  set(CMAKE_SYSTEM_NAME WindowsPhone)
+  set(CMAKE_SYSTEM_VERSION 8.1)
+
+Cross Compiling for Windows Store
+---------------------------------
+
+A toolchain file to configure a Visual Studio generator for
+Windows Store may look like this:
+
+.. code-block:: cmake
+
+  set(CMAKE_SYSTEM_NAME WindowsStore)
+  set(CMAKE_SYSTEM_VERSION 8.1)
diff --git a/Help/manual/cmake-variables.7.rst b/Help/manual/cmake-variables.7.rst
index df434c5..1deb8bb 100644
--- a/Help/manual/cmake-variables.7.rst
+++ b/Help/manual/cmake-variables.7.rst
@@ -37,6 +37,7 @@
    /variable/CMAKE_EXTRA_GENERATOR
    /variable/CMAKE_EXTRA_SHARED_LIBRARY_SUFFIXES
    /variable/CMAKE_GENERATOR
+   /variable/CMAKE_GENERATOR_PLATFORM
    /variable/CMAKE_GENERATOR_TOOLSET
    /variable/CMAKE_HOME_DIRECTORY
    /variable/CMAKE_IMPORT_LIBRARY_PREFIX
@@ -73,6 +74,8 @@
    /variable/CMAKE_VS_INTEL_Fortran_PROJECT_VERSION
    /variable/CMAKE_VS_MSBUILD_COMMAND
    /variable/CMAKE_VS_MSDEV_COMMAND
+   /variable/CMAKE_VS_NsightTegra_VERSION
+   /variable/CMAKE_VS_PLATFORM_NAME
    /variable/CMAKE_VS_PLATFORM_TOOLSET
    /variable/CMAKE_XCODE_PLATFORM_TOOLSET
    /variable/PROJECT_BINARY_DIR
@@ -128,6 +131,7 @@
    /variable/CMAKE_INCLUDE_DIRECTORIES_BEFORE
    /variable/CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE
    /variable/CMAKE_INSTALL_DEFAULT_COMPONENT_NAME
+   /variable/CMAKE_INSTALL_MESSAGE
    /variable/CMAKE_INSTALL_PREFIX
    /variable/CMAKE_LIBRARY_PATH
    /variable/CMAKE_MFC_FLAG
@@ -178,6 +182,7 @@
    /variable/MSVC10
    /variable/MSVC11
    /variable/MSVC12
+   /variable/MSVC14
    /variable/MSVC60
    /variable/MSVC70
    /variable/MSVC71
@@ -188,6 +193,9 @@
    /variable/MSVC_VERSION
    /variable/UNIX
    /variable/WIN32
+   /variable/WINCE
+   /variable/WINDOWS_PHONE
+   /variable/WINDOWS_STORE
    /variable/XCODE_VERSION
 
 Variables that Control the Build
@@ -196,6 +204,8 @@
 .. toctree::
    :maxdepth: 1
 
+   /variable/CMAKE_ANDROID_API
+   /variable/CMAKE_ANDROID_GUI
    /variable/CMAKE_ARCHIVE_OUTPUT_DIRECTORY
    /variable/CMAKE_AUTOMOC_MOC_OPTIONS
    /variable/CMAKE_AUTOMOC
@@ -250,6 +260,7 @@
    /variable/CMAKE_USE_RELATIVE_PATHS
    /variable/CMAKE_VISIBILITY_INLINES_HIDDEN
    /variable/CMAKE_WIN32_EXECUTABLE
+   /variable/CMAKE_XCODE_ATTRIBUTE_an-attribute
    /variable/EXECUTABLE_OUTPUT_PATH
    /variable/LIBRARY_OUTPUT_PATH
 
@@ -341,7 +352,9 @@
    /variable/CTEST_HG_UPDATE_OPTIONS
    /variable/CTEST_MEMORYCHECK_COMMAND
    /variable/CTEST_MEMORYCHECK_COMMAND_OPTIONS
+   /variable/CTEST_MEMORYCHECK_SANITIZER_OPTIONS
    /variable/CTEST_MEMORYCHECK_SUPPRESSIONS_FILE
+   /variable/CTEST_MEMORYCHECK_TYPE
    /variable/CTEST_NIGHTLY_START_TIME
    /variable/CTEST_P4_CLIENT
    /variable/CTEST_P4_COMMAND
@@ -357,6 +370,7 @@
    /variable/CTEST_TRIGGER_SITE
    /variable/CTEST_UPDATE_COMMAND
    /variable/CTEST_UPDATE_OPTIONS
+   /variable/CTEST_UPDATE_VERSION_ONLY
    /variable/CTEST_USE_LAUNCHERS
 
 Variables for CPack
diff --git a/Help/manual/cmake.1.rst b/Help/manual/cmake.1.rst
index 5743ab7..8dfc16a 100644
--- a/Help/manual/cmake.1.rst
+++ b/Help/manual/cmake.1.rst
@@ -38,7 +38,7 @@
  For true platform independence, CMake provides a list of commands
  that can be used on all systems.  Run with -E help for the usage
  information.  Commands available are: chdir, compare_files, copy,
- copy_directory, copy_if_different, echo, echo_append, environment,
+ copy_directory, copy_if_different, echo, echo_append, env, environment,
  make_directory, md5sum, remove, remove_directory, rename, sleep, tar, time,
  touch, touch_nocreate.  In addition, some platform specific commands
  are available.  On Windows: delete_regv, write_regv.  On
diff --git a/Help/manual/ctest.1.rst b/Help/manual/ctest.1.rst
index a57a8f0..03e86af 100644
--- a/Help/manual/ctest.1.rst
+++ b/Help/manual/ctest.1.rst
@@ -111,7 +111,7 @@
 ``-D <dashboard>, --dashboard <dashboard>``
  Execute dashboard test
 
- This option tells ctest to act as a Dart client and perform a
+ This option tells ctest to act as a CDash client and perform a
  dashboard test.  All tests are <Mode><Test>, where Mode can be
  Experimental, Nightly, and Continuous, and Test can be Start,
  Update, Configure, Build, Test, Coverage, and Submit.
@@ -127,14 +127,14 @@
 ``-M <model>, --test-model <model>``
  Sets the model for a dashboard
 
- This option tells ctest to act as a Dart client where the TestModel
+ This option tells ctest to act as a CDash client where the TestModel
  can be Experimental, Nightly, and Continuous.  Combining -M and -T
  is similar to -D
 
 ``-T <action>, --test-action <action>``
  Sets the dashboard action to perform
 
- This option tells ctest to act as a Dart client and perform some
+ This option tells ctest to act as a CDash client and perform some
  action such as start, build, test etc.  Combining -M and -T is
  similar to -D
 
@@ -258,6 +258,9 @@
 ``--build-generator``
  Specify the generator to use.
 
+``--build-generator-platform``
+ Specify the generator-specific platform.
+
 ``--build-generator-toolset``
  Specify the generator-specific toolset.
 
@@ -325,11 +328,8 @@
  used to detect implicit dependencies in a test suite.
 
 ``--submit-index``
- Submit individual dashboard tests with specific index
-
- This option allows performing the same CTest action (such as test)
- multiple times and submit all stages to the same dashboard (Dart2
- required).  Each execution requires different index.
+ Legacy option for old Dart2 dashboard server feature.
+ Do not use.
 
 ``--timeout <seconds>``
  Set a global timeout on all tests.
@@ -668,6 +668,15 @@
   * :module:`CTest` module variable: ``UPDATE_TYPE`` if set,
     else ``CTEST_UPDATE_TYPE``
 
+``UpdateVersionOnly``
+  Specify that you want the version control update command to only
+  discover the current version that is checked out, and not to update
+  to a different version.
+
+  * `CTest Script`_ variable: :variable:`CTEST_UPDATE_VERSION_ONLY`
+
+
+
 Additional configuration settings include:
 
 ``NightlyStartTime``
@@ -812,6 +821,18 @@
   * `CTest Script`_ variable: :variable:`CTEST_MEMORYCHECK_COMMAND_OPTIONS`
   * :module:`CTest` module variable: ``MEMORYCHECK_COMMAND_OPTIONS``
 
+``MemoryCheckType``
+  Specify the type of memory checking to perform.
+
+  * `CTest Script`_ variable: :variable:`CTEST_MEMORYCHECK_TYPE`
+  * :module:`CTest` module variable: ``MEMORYCHECK_TYPE``
+
+``MemoryCheckSanitizerOptions``
+  Specify options to sanitizers when running with a sanitize-enabled build.
+
+  * `CTest Script`_ variable: :variable:`CTEST_MEMORYCHECK_SANITIZER_OPTIONS`
+  * :module:`CTest` module variable: ``MEMORYCHECK_SANITIZER_OPTIONS``
+
 ``MemoryCheckSuppressionFile``
   Specify a file containing suppression rules for the
   ``MemoryCheckCommand`` tool.  It will be passed with options
diff --git a/Help/module/CPackIFW.rst b/Help/module/CPackIFW.rst
new file mode 100644
index 0000000..ea05796
--- /dev/null
+++ b/Help/module/CPackIFW.rst
@@ -0,0 +1 @@
+.. cmake-module:: ../../Modules/CPackIFW.cmake
diff --git a/Help/module/CheckFortranSourceCompiles.rst b/Help/module/CheckFortranSourceCompiles.rst
new file mode 100644
index 0000000..b749a2a
--- /dev/null
+++ b/Help/module/CheckFortranSourceCompiles.rst
@@ -0,0 +1 @@
+.. cmake-module:: ../../Modules/CheckFortranSourceCompiles.cmake
diff --git a/Help/module/FindITK.rst b/Help/module/FindITK.rst
index dbfabbd..21a922f 100644
--- a/Help/module/FindITK.rst
+++ b/Help/module/FindITK.rst
@@ -1 +1,10 @@
-.. cmake-module:: ../../Modules/FindITK.cmake
+FindITK
+-------
+
+This module no longer exists.
+
+This module existed in versions of CMake prior to 3.1, but became
+only a thin wrapper around ``find_package(ITK NO_MODULE)`` to
+provide compatibility for projects using long-outdated conventions.
+Now ``find_package(ITK)`` will search for ``ITKConfig.cmake``
+directly.
diff --git a/Help/module/FindIce.rst b/Help/module/FindIce.rst
new file mode 100644
index 0000000..3af9405
--- /dev/null
+++ b/Help/module/FindIce.rst
@@ -0,0 +1 @@
+.. cmake-module:: ../../Modules/FindIce.cmake
diff --git a/Help/module/FindVTK.rst b/Help/module/FindVTK.rst
index f9c1efe..3bc67c5 100644
--- a/Help/module/FindVTK.rst
+++ b/Help/module/FindVTK.rst
@@ -1 +1,10 @@
-.. cmake-module:: ../../Modules/FindVTK.cmake
+FindVTK
+-------
+
+This module no longer exists.
+
+This module existed in versions of CMake prior to 3.1, but became
+only a thin wrapper around ``find_package(VTK NO_MODULE)`` to
+provide compatibility for projects using long-outdated conventions.
+Now ``find_package(VTK)`` will search for ``VTKConfig.cmake``
+directly.
diff --git a/Help/module/FindXerces.rst b/Help/module/FindXerces.rst
new file mode 100644
index 0000000..166d8dd
--- /dev/null
+++ b/Help/module/FindXerces.rst
@@ -0,0 +1 @@
+.. cmake-module:: ../../Modules/FindXerces.cmake
diff --git a/Help/policy/CMP0022.rst b/Help/policy/CMP0022.rst
index 16a5bc3..22c7c4f 100644
--- a/Help/policy/CMP0022.rst
+++ b/Help/policy/CMP0022.rst
@@ -22,7 +22,7 @@
 target_link_libraries command will no longer populate the properties
 matching LINK_INTERFACE_LIBRARIES(_<CONFIG>)? if this policy is NEW.
 
-Warning-free future-compatible code which works with CMake 2.8.9 onwards
+Warning-free future-compatible code which works with CMake 2.8.7 onwards
 can be written by using the ``LINK_PRIVATE`` and ``LINK_PUBLIC`` keywords
 of :command:`target_link_libraries`.
 
diff --git a/Help/policy/CMP0054.rst b/Help/policy/CMP0054.rst
new file mode 100644
index 0000000..dffee5e
--- /dev/null
+++ b/Help/policy/CMP0054.rst
@@ -0,0 +1,18 @@
+CMP0054
+-------
+
+Only interpret :command:`if` arguments as variables or keywords when unquoted.
+
+CMake 3.1 and above no longer dereference variables or interpret keywords
+in an :command:`if` command argument when it is a :ref:`Quoted Argument`
+or a :ref:`Bracket Argument`.
+
+The ``OLD`` behavior for this policy is to dereference variables and
+interpret keywords even if they are quoted or bracketed.
+The ``NEW`` behavior is to not dereference variables or interpret keywords
+that have been quoted or bracketed.
+
+This policy was introduced in CMake version 3.1.
+CMake version |release| warns when the policy is not set and uses
+``OLD`` behavior.  Use the :command:`cmake_policy` command to set
+it to ``OLD`` or ``NEW`` explicitly.
diff --git a/Help/prop_dir/COMPILE_DEFINITIONS_CONFIG.rst b/Help/prop_dir/COMPILE_DEFINITIONS_CONFIG.rst
index c22606b..a6af45f 100644
--- a/Help/prop_dir/COMPILE_DEFINITIONS_CONFIG.rst
+++ b/Help/prop_dir/COMPILE_DEFINITIONS_CONFIG.rst
@@ -1,6 +1,8 @@
 COMPILE_DEFINITIONS_<CONFIG>
 ----------------------------
 
+Ignored.  See CMake Policy :policy:`CMP0043`.
+
 Per-configuration preprocessor definitions in a directory.
 
 This is the configuration-specific version of :prop_dir:`COMPILE_DEFINITIONS`
diff --git a/Help/prop_inst/CPACK_WIX_ACL.rst b/Help/prop_inst/CPACK_WIX_ACL.rst
new file mode 100644
index 0000000..4e13ec4
--- /dev/null
+++ b/Help/prop_inst/CPACK_WIX_ACL.rst
@@ -0,0 +1,19 @@
+CPACK_WIX_ACL
+-------------
+
+Specifies access permissions for files or directories
+installed by a WiX installer.
+
+The property can contain multiple list entries,
+each of which has to match the following format.
+
+::
+
+  <user>[@<domain>]=<permission>[,<permission>]
+
+``<user>`` and ``<domain>`` specify the windows user and domain for which the
+``<Permission>`` element should be generated.
+
+``<permission>`` is any of the YesNoType attributes listed here::
+
+ http://wixtoolset.org/documentation/manual/v3/xsd/wix/permission.html
diff --git a/Help/prop_sf/COMPILE_DEFINITIONS_CONFIG.rst b/Help/prop_sf/COMPILE_DEFINITIONS_CONFIG.rst
index e695f38..8487076 100644
--- a/Help/prop_sf/COMPILE_DEFINITIONS_CONFIG.rst
+++ b/Help/prop_sf/COMPILE_DEFINITIONS_CONFIG.rst
@@ -1,6 +1,8 @@
 COMPILE_DEFINITIONS_<CONFIG>
 ----------------------------
 
+Ignored.  See CMake Policy :policy:`CMP0043`.
+
 Per-configuration preprocessor definitions on a source file.
 
 This is the configuration-specific version of COMPILE_DEFINITIONS.
diff --git a/Help/prop_sf/VS_DEPLOYMENT_CONTENT.rst b/Help/prop_sf/VS_DEPLOYMENT_CONTENT.rst
new file mode 100644
index 0000000..9fb3ba3
--- /dev/null
+++ b/Help/prop_sf/VS_DEPLOYMENT_CONTENT.rst
@@ -0,0 +1,11 @@
+VS_DEPLOYMENT_CONTENT
+---------------------
+
+Mark a source file as content for deployment with a Windows Phone or
+Windows Store application when built with a Visual Studio generator.
+The value must evaluate to either ``1`` or ``0`` and may use
+:manual:`generator expressions <cmake-generator-expressions(7)>`
+to make the choice based on the build configuration.
+The ``.vcxproj`` file entry for the source file will be
+marked either ``DeploymentContent`` or ``ExcludedFromBuild``
+for values ``1`` and ``0``, respectively.
diff --git a/Help/prop_sf/VS_SHADER_TYPE.rst b/Help/prop_sf/VS_SHADER_TYPE.rst
new file mode 100644
index 0000000..6880256
--- /dev/null
+++ b/Help/prop_sf/VS_SHADER_TYPE.rst
@@ -0,0 +1,4 @@
+VS_SHADER_TYPE
+--------------
+
+Set the VS shader type of a ``.hlsl`` source file.
diff --git a/Help/prop_tgt/ANDROID_API.rst b/Help/prop_tgt/ANDROID_API.rst
new file mode 100644
index 0000000..714ad58
--- /dev/null
+++ b/Help/prop_tgt/ANDROID_API.rst
@@ -0,0 +1,7 @@
+ANDROID_API
+-----------
+
+Set the Android Target API version (e.g. ``15``).  The version number
+must be a positive decimal integer.  This property is initialized by
+the value of the :variable:`CMAKE_ANDROID_API` variable if it is set
+when a target is created.
diff --git a/Help/prop_tgt/ANDROID_GUI.rst b/Help/prop_tgt/ANDROID_GUI.rst
new file mode 100644
index 0000000..90d2428
--- /dev/null
+++ b/Help/prop_tgt/ANDROID_GUI.rst
@@ -0,0 +1,9 @@
+ANDROID_GUI
+-----------
+
+Build an executable as an application package on Android.
+
+When this property is set to true the executable when built for Android
+will be created as an application package.  This property is initialized
+by the value of the :variable:`CMAKE_ANDROID_GUI` variable if it is set
+when a target is created.
diff --git a/Help/prop_tgt/COMPILE_DEFINITIONS_CONFIG.rst b/Help/prop_tgt/COMPILE_DEFINITIONS_CONFIG.rst
index e359d2c..84bd5e4 100644
--- a/Help/prop_tgt/COMPILE_DEFINITIONS_CONFIG.rst
+++ b/Help/prop_tgt/COMPILE_DEFINITIONS_CONFIG.rst
@@ -1,6 +1,8 @@
 COMPILE_DEFINITIONS_<CONFIG>
 ----------------------------
 
+Ignored.  See CMake Policy :policy:`CMP0043`.
+
 Per-configuration preprocessor definitions on a target.
 
 This is the configuration-specific version of :prop_tgt:`COMPILE_DEFINITIONS`
diff --git a/Help/prop_tgt/VS_WINRT_COMPONENT.rst b/Help/prop_tgt/VS_WINRT_COMPONENT.rst
new file mode 100644
index 0000000..e160bd6
--- /dev/null
+++ b/Help/prop_tgt/VS_WINRT_COMPONENT.rst
@@ -0,0 +1,11 @@
+VS_WINRT_COMPONENT
+------------------
+
+Mark a target as a Windows Runtime component for the Visual Studio generator.
+Compile the target with ``C++/CX`` language extensions for Windows Runtime.
+For ``SHARED`` and ``MODULE`` libraries, this also defines the
+``_WINRT_DLL`` preprocessor macro.
+
+.. note::
+  Currently this is implemented only by Visual Studio generators.
+  Support may be added to other generators in the future.
diff --git a/Help/prop_tgt/VS_WINRT_EXTENSIONS.rst b/Help/prop_tgt/VS_WINRT_EXTENSIONS.rst
index cc6fb16..d1cba34 100644
--- a/Help/prop_tgt/VS_WINRT_EXTENSIONS.rst
+++ b/Help/prop_tgt/VS_WINRT_EXTENSIONS.rst
@@ -1,6 +1,5 @@
 VS_WINRT_EXTENSIONS
 -------------------
 
-Visual Studio project C++/CX language extensions for Windows Runtime
-
-Can be set to enable C++/CX language extensions.
+Deprecated.  Use :prop_tgt:`VS_WINRT_COMPONENT` instead.
+This property was an experimental partial implementation of that one.
diff --git a/Help/prop_tgt/XCODE_ATTRIBUTE_an-attribute.rst b/Help/prop_tgt/XCODE_ATTRIBUTE_an-attribute.rst
index 0be313c..de98c37 100644
--- a/Help/prop_tgt/XCODE_ATTRIBUTE_an-attribute.rst
+++ b/Help/prop_tgt/XCODE_ATTRIBUTE_an-attribute.rst
@@ -5,3 +5,6 @@
 
 Tell the Xcode generator to set '<an-attribute>' to a given value in
 the generated Xcode project.  Ignored on other generators.
+
+See the :variable:`CMAKE_XCODE_ATTRIBUTE_<an-attribute>` variable
+to set attributes on all targets in a directory tree.
diff --git a/Help/release/3.1.0.rst b/Help/release/3.1.0.rst
new file mode 100644
index 0000000..652bcd3
--- /dev/null
+++ b/Help/release/3.1.0.rst
@@ -0,0 +1,381 @@
+CMake 3.1.0 Release Notes
+*************************
+
+.. only:: html
+
+  .. contents::
+
+Changes made since CMake 3.0.0 include the following.
+
+Documentation Changes
+=====================
+
+* A new :manual:`cmake-compile-features(7)` manual was added.
+
+New Features
+============
+
+Generators
+----------
+
+* A :generator:`Visual Studio 14` generator was added.
+
+Windows Phone and Windows Store
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+* Generators for Visual Studio 11 (2012) and above learned to generate
+  projects for Windows Phone and Windows Store.  One may set the
+  :variable:`CMAKE_SYSTEM_NAME` variable to ``WindowsPhone``
+  or ``WindowsStore`` on the :manual:`cmake(1)` command-line
+  or in a :variable:`CMAKE_TOOLCHAIN_FILE` to activate these platforms.
+  Also set :variable:`CMAKE_SYSTEM_VERSION` to ``8.0`` or ``8.1`` to
+  specify the version of Windows to be targeted.
+
+NVIDIA Nsight Tegra
+^^^^^^^^^^^^^^^^^^^
+
+* Generators for Visual Studio 10 (2010) and above learned to generate
+  projects for NVIDIA Nsight Tegra Visual Studio Edition.  One may set
+  the :variable:`CMAKE_SYSTEM_NAME` variable to ``Android`` on the
+  :manual:`cmake(1)` command-line or in a :variable:`CMAKE_TOOLCHAIN_FILE`
+  to activate this platform.
+
+Syntax
+------
+
+* The :manual:`cmake-language(7)` syntax for :ref:`Variable References` and
+  :ref:`Escape Sequences` was simplified in order to allow a much faster
+  implementation.  See policy :policy:`CMP0053`.
+
+* The :command:`if` command no longer automatically dereferences
+  variables named in quoted or bracket arguments.  See policy
+  :policy:`CMP0054`.
+
+Commands
+--------
+
+* The :command:`add_custom_command` command learned to interpret
+  :manual:`cmake-generator-expressions(7)` in arguments to ``DEPENDS``.
+
+* The :command:`export(PACKAGE)` command learned to check the
+  :variable:`CMAKE_EXPORT_NO_PACKAGE_REGISTRY` variable to skip
+  exporting the package.
+
+* The :command:`file(STRINGS)` command gained a new ``ENCODING``
+  option to enable extraction of ``UTF-8`` strings.
+
+* The :command:`find_package` command learned to check the
+  :variable:`CMAKE_FIND_PACKAGE_NO_PACKAGE_REGISTRY` and
+  :variable:`CMAKE_FIND_PACKAGE_NO_SYSTEM_PACKAGE_REGISTRY`
+  variables to skip searching the package registries.
+
+* The :command:`install` command learned a ``MESSAGE_NEVER`` option
+  to avoid output during installation.
+
+* The :command:`string` command learned a new ``GENEX_STRIP`` subcommand
+  which removes
+  :manual:`generator expression <cmake-generator-expressions(7)>`.
+
+* The :command:`string` command learned a new ``UUID`` subcommand
+  to generate a univerally unique identifier.
+
+* New :command:`target_compile_features` command allows populating the
+  :prop_tgt:`COMPILE_FEATURES` target property, just like any other
+  build variable.
+
+* The :command:`target_sources` command was added to add to the
+  :prop_tgt:`SOURCES` target property.
+
+Variables
+---------
+
+* The Visual Studio generators for versions 8 (2005) and above
+  learned to read the target platform name from a new
+  :variable:`CMAKE_GENERATOR_PLATFORM` variable when it is
+  not specified as part of the generator name.  The platform
+  name may be specified on the :manual:`cmake(1)` command line
+  with the ``-A`` option, e.g. ``-G "Visual Studio 12 2013" -A x64``.
+
+* The :variable:`CMAKE_GENERATOR_TOOLSET` variable may now be
+  initialized in a toolchain file specified by the
+  :variable:`CMAKE_TOOLCHAIN_FILE` variable.  This is useful
+  when cross-compiling with the Xcode or Visual Studio
+  generators.
+
+* The :variable:`CMAKE_INSTALL_MESSAGE` variable was introduced to
+  optionally reduce output installation.
+
+Properties
+----------
+
+* New :prop_tgt:`CXX_STANDARD` and :prop_tgt:`CXX_EXTENSIONS` target
+  properties may specify values which CMake uses to compute required
+  compile options such as ``-std=c++11`` or ``-std=gnu++11``. The
+  :variable:`CMAKE_CXX_STANDARD` and :variable:`CMAKE_CXX_EXTENSIONS`
+  variables may be set to initialize the target properties.
+
+* New :prop_tgt:`C_STANDARD` and :prop_tgt:`C_EXTENSIONS` target
+  properties may specify values which CMake uses to compute required
+  compile options such as ``-std=c11`` or ``-std=gnu11``. The
+  :variable:`CMAKE_C_STANDARD` and :variable:`CMAKE_C_EXTENSIONS`
+  variables may be set to initialize the target properties.
+
+* New :prop_tgt:`COMPILE_FEATURES` target property may contain a list
+  of features required to compile a target.  CMake uses this
+  information to ensure that the compiler in use is capable of building
+  the target, and to add any necessary compile flags to support language
+  features.
+
+* New :prop_tgt:`COMPILE_PDB_NAME` and
+  :prop_tgt:`COMPILE_PDB_OUTPUT_DIRECTORY` target properties
+  were introduced to specify the MSVC compiler program database
+  file location (``cl /Fd``).  This complements the existing
+  :prop_tgt:`PDB_NAME` and :prop_tgt:`PDB_OUTPUT_DIRECTORY`
+  target properties that specify the linker program database
+  file location (``link /pdb``).
+
+* The :prop_tgt:`INTERFACE_LINK_LIBRARIES` target property now supports
+  a ``$<LINK_ONLY:...>``
+  :manual:`generator expression <cmake-generator-expressions(7)>`.
+
+* A new :prop_tgt:`INTERFACE_SOURCES` target property was introduced. This is
+  consumed by dependent targets, which compile and link the listed sources.
+
+* The :prop_tgt:`SOURCES` target property now contains
+  :manual:`generator expression <cmake-generator-expressions(7)>`
+  such as ``TARGET_OBJECTS`` when read at configure time, if
+  policy :policy:`CMP0051` is ``NEW``.
+
+* The :prop_tgt:`SOURCES` target property now generally supports
+  :manual:`generator expression <cmake-generator-expressions(7)>`.  The
+  generator expressions may be used in the :command:`add_library` and
+  :command:`add_executable` commands.
+
+* It is now possible to write and append to the :prop_tgt:`SOURCES` target
+  property.  The :variable:`CMAKE_DEBUG_TARGET_PROPERTIES` variable may be
+  used to trace the origin of sources.
+
+* A :prop_sf:`VS_DEPLOYMENT_CONTENT` source file property was added
+  to tell the Visual Studio generators to mark content for deployment
+  in Windows Phone and Windows Store projects.
+
+* The :prop_tgt:`VS_WINRT_COMPONENT` target property was created to
+  tell Visual Studio generators to compile a shared library as a
+  Windows Runtime (WinRT) component.
+
+* The :generator:`Xcode` generator learned to check source
+  file properties  :prop_sf:`XCODE_EXPLICIT_FILE_TYPE` and
+  :prop_sf:`XCODE_LAST_KNOWN_FILE_TYPE` for a custom Xcode
+  file reference type.
+
+Modules
+-------
+
+* The :module:`BundleUtilities` module learned to resolve and replace
+  ``@rpath`` placeholders on OS X to correctly bundle applications
+  using them.
+
+* The :module:`CMakePackageConfigHelpers` module
+  :command:`configure_package_config_file` command learned a new
+  ``INSTALL_PREFIX`` option to generate package configuration files
+  meant for a prefix other than :variable:`CMAKE_INSTALL_PREFIX`.
+
+* The :module:`CheckFortranSourceCompiles` module was added to
+  provide a ``CHECK_Fortran_SOURCE_COMPILES`` macro.
+
+* The :module:`ExternalData` module learned to tolerate a ``DATA{}``
+  reference to a missing source file with a warning instead of
+  rejecting it with an error.  This helps developers write new
+  ``DATA{}`` references to test reference outputs that have not
+  yet been created.
+
+* The :module:`ExternalProject` module learned to support lzma-compressed
+  source tarballs with ``.7z``, ``.tar.xz``, and ``.txz`` extensions.
+
+* The :module:`ExternalProject` module ``ExternalProject_Add`` command
+  learned a new ``BUILD_ALWAYS`` option to cause the external project
+  build step to run every time the host project is built.
+
+* The :module:`ExternalProject` module ``ExternalProject_Add`` command
+  learned a new ``EXCLUDE_FROM_ALL`` option to cause the external
+  project target to have the :prop_tgt:`EXCLUDE_FROM_ALL` target
+  property set.
+
+* The :module:`ExternalProject` module ``ExternalProject_Add_Step`` command
+  learned a new ``EXCLUDE_FROM_MAIN`` option to cause the step to not be
+  a direct dependency of the main external project target.
+
+* The :module:`ExternalProject` module ``ExternalProject_Add`` command
+  learned a new ``DOWNLOAD_NO_PROGRESS`` option to disable progress
+  output while downloading the source tarball.
+
+* The :module:`FeatureSummary` module ``feature_summary`` API
+  learned to accept multiple values for the ``WHAT`` option and
+  combine them appropriately.
+
+* The :module:`FindCUDA` module learned to support ``fatbin`` and ``cubin``
+  modules.
+
+* The :module:`FindGTest` module ``gtest_add_tests`` macro learned
+  a new ``AUTO`` option to automatically read the :prop_tgt:`SOURCES`
+  target property of the test executable and scan the source files
+  for tests to be added.
+
+* The :module:`FindGLEW` module now provides imported targets.
+
+* The :module:`FindGLUT` module now provides imported targets.
+
+* The :module:`FindHg` module gained a new ``Hg_WC_INFO`` macro to
+  help run ``hg`` to extract information about a Mercurial work copy.
+
+* The :module:`FindOpenCL` module was introduced.
+
+* The :module:`FindOpenGL` module now provides imported targets
+  ``OpenGL::GL`` and ``OpenGL::GLU`` when the libraries are found.
+
+* The :module:`FindOpenMP` module learned to support Fortran.
+
+* The :module:`FindPkgConfig` module learned to use the ``PKG_CONFIG``
+  environment variable value as the ``pkg-config`` executable, if set.
+
+* The :module:`FindVTK` module dropped support for finding VTK 4.0.
+  It is now a thin-wrapper around ``find_package(VTK ... NO_MODULE)``.
+  This produces much clearer error messages when VTK is not found.
+
+* The :module:`FindZLIB` module now provides imported targets.
+
+* The :module:`GenerateExportHeader` module ``generate_export_header``
+  function learned to allow use with :ref:`Object Libraries`.
+
+* The :module:`InstallRequiredSystemLibraries` module gained a new
+  ``CMAKE_INSTALL_OPENMP_LIBRARIES`` option to install MSVC OpenMP
+  runtime libraries.
+
+* The :module:`UseSWIG` module learned to detect the module name
+  from ``.i`` source files if possible to avoid the need to set
+  the ``SWIG_MODULE_NAME`` source file property explicitly.
+
+* The :module:`WriteCompilerDetectionHeader` module was added to allow
+  creation of a portable header file for compiler optional feature detection.
+
+Generator Expressions
+---------------------
+
+* New ``COMPILE_FEATURES``
+  :manual:`generator expression <cmake-generator-expressions(7)>` allows
+  setting build properties based on available compiler features.
+
+CTest
+-----
+
+* The :command:`ctest_coverage` command learned to read variable
+  ``CTEST_COVERAGE_EXTRA_FLAGS`` to set ``CoverageExtraFlags``.
+
+* The :command:`ctest_coverage` command learned to support
+  Intel coverage files with the ``codecov`` tool.
+
+* The :command:`ctest_memcheck` command learned to support sanitizer
+  modes, including ``AddressSanitizer``, ``MemorySanitizer``,
+  ``ThreadSanitizer``, and ``UndefinedBehaviorSanitizer``.
+  Options may be set using the new
+  :variable:`CTEST_MEMORYCHECK_SANITIZER_OPTIONS` variable.
+
+CPack
+-----
+
+* :manual:`cpack(1)` gained an ``IFW`` generator to package using
+  Qt Framework Installer tools.  See the :module:`CPackIFW` module.
+
+* :manual:`cpack(1)` gained ``7Z`` and ``TXZ`` generators supporting
+  lzma-compressed archives.
+
+* The :module:`CPackDeb` module learned a new
+  :variable:`CPACK_DEBIAN_COMPRESSION_TYPE` variable to set the
+  tarball compression type.
+
+* The :manual:`cpack(1)` ``WiX`` generator learned to support
+  a :prop_inst:`CPACK_WIX_ACL` installed file property to
+  specify an Access Control List.
+
+Other
+-----
+
+* The :manual:`cmake(1)` ``-E`` option learned a new ``env`` command.
+
+* The :manual:`cmake(1)` ``-E tar`` command learned to support
+  lzma-compressed files.
+
+* :ref:`Object Libraries` may now have extra sources that do not
+  compile to object files so long as they would not affect linking
+  of a normal library (e.g. ``.dat`` is okay but not ``.def``).
+
+* Visual Studio generators for VS 8 and later learned to support
+  the ``ASM_MASM`` language.
+
+* The Visual Studio generators learned to treat ``.hlsl`` source
+  files as High Level Shading Language sources (using ``FXCompile``
+  in ``.vcxproj`` files).  A :prop_sf:`VS_SHADER_TYPE` source file
+  property was added to specify the Shader Type.
+
+New Diagnostics
+===============
+
+* Policy :policy:`CMP0052` introduced to control directories in the
+  :prop_tgt:`INTERFACE_INCLUDE_DIRECTORIES` of exported targets.
+
+Deprecated and Removed Features
+===============================
+
+* In CMake 3.0 the :command:`target_link_libraries` command
+  accidentally began allowing unquoted arguments to use
+  :manual:`generator expressions <cmake-generator-expressions(7)>`
+  containing a (``;`` separated) list within them.  For example::
+
+    set(libs B C)
+    target_link_libraries(A PUBLIC $<BUILD_INTERFACE:${libs}>)
+
+  This is equivalent to writing::
+
+    target_link_libraries(A PUBLIC $<BUILD_INTERFACE:B C>)
+
+  and was never intended to work.  It did not work in CMake 2.8.12.
+  Such generator expressions should be in quoted arguments::
+
+    set(libs B C)
+    target_link_libraries(A PUBLIC "$<BUILD_INTERFACE:${libs}>")
+
+  CMake 3.1 again requires the quotes for this to work correctly.
+
+* Callbacks established by the :command:`variable_watch` command will no
+  longer receive the ``ALLOWED_UNKNOWN_READ_ACCESS`` access type when
+  the undocumented ``CMAKE_ALLOW_UNKNOWN_VARIABLE_READ_ACCESS`` variable is
+  set.  Uninitialized variable accesses will always be reported as
+  ``UNKNOWN_READ_ACCESS``.
+
+* The :module:`CMakeDetermineVSServicePack` module now warns that
+  it is deprecated and should not longer be used.  Use the
+  :variable:`CMAKE_<LANG>_COMPILER_VERSION` variable instead.
+
+Other Changes
+=============
+
+* The :manual:`cmake-gui(1)` learned to capture output from child
+  processes started by the :command:`execute_process` command
+  and display it in the output window.
+
+* The :manual:`cmake-language(7)` internal implementation of generator
+  expression and list expansion parsers have been optimized and shows
+  non-trivial speedup on large projects.
+
+* The Makefile generators learned to use response files with GNU tools
+  on Windows to pass library directories and names to the linker.
+
+* When generating linker command-lines, CMake now avoids repeating
+  items corresponding to SHARED library targets.
+
+* Support for the Open Watcom compiler has been overhauled.
+  The :variable:`CMAKE_<LANG>_COMPILER_ID` is now ``OpenWatcom``,
+  and the :variable:`CMAKE_<LANG>_COMPILER_VERSION` now uses
+  the Open Watcom external version numbering.  The external
+  version numbers are lower than the internal version number
+  by 11.
diff --git a/Help/release/dev/0-sample-topic.rst b/Help/release/dev/0-sample-topic.rst
deleted file mode 100644
index e4cc01e..0000000
--- a/Help/release/dev/0-sample-topic.rst
+++ /dev/null
@@ -1,7 +0,0 @@
-0-sample-topic
---------------
-
-* This is a sample release note for the change in a topic.
-  Developers should add similar notes for each topic branch
-  making a noteworthy change.  Each document should be named
-  and titled to match the topic name to avoid merge conflicts.
diff --git a/Help/release/dev/CMP0052.rst b/Help/release/dev/CMP0052.rst
deleted file mode 100644
index adb3d44..0000000
--- a/Help/release/dev/CMP0052.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-CMP0052
--------
-
-* Policy :policy:`CMP0052` introduced to control directories in the
-  :prop_tgt:`INTERFACE_INCLUDE_DIRECTORIES` of exported targets.
diff --git a/Help/release/dev/CMP0053.rst b/Help/release/dev/CMP0053.rst
deleted file mode 100644
index 3b835fb..0000000
--- a/Help/release/dev/CMP0053.rst
+++ /dev/null
@@ -1,6 +0,0 @@
-CMP0053
--------
-
-* The :manual:`cmake-language(7)` syntax for :ref:`Variable References` and
-  :ref:`Escape Sequences` was simplified in order to allow a much faster
-  implementation.  See policy :policy:`CMP0053`.
diff --git a/Help/release/dev/CMakeDetermineVSServicePack.rst b/Help/release/dev/CMakeDetermineVSServicePack.rst
deleted file mode 100644
index d9d7b41..0000000
--- a/Help/release/dev/CMakeDetermineVSServicePack.rst
+++ /dev/null
@@ -1,6 +0,0 @@
-CMakeDetermineVSServicePack
----------------------------
-
-* The :module:`CMakeDetermineVSServicePack` module now warns that
-  it is deprecated and should not longer be used.  Use the
-  :variable:`CMAKE_<LANG>_COMPILER_VERSION` variable instead.
diff --git a/Help/release/dev/ExternalData-missing-not-fatal.rst b/Help/release/dev/ExternalData-missing-not-fatal.rst
deleted file mode 100644
index e9f1f04..0000000
--- a/Help/release/dev/ExternalData-missing-not-fatal.rst
+++ /dev/null
@@ -1,8 +0,0 @@
-ExternalData-missing-not-fatal
-------------------------------
-
-* The :module:`ExternalData` module learned to tolerate a ``DATA{}``
-  reference to a missing source file with a warning instead of
-  rejecting it with an error.  This helps developers write new
-  ``DATA{}`` references to test reference outputs that have not
-  yet been created.
diff --git a/Help/release/dev/ExternalProject-BUILD_ALWAYS.rst b/Help/release/dev/ExternalProject-BUILD_ALWAYS.rst
deleted file mode 100644
index 5384671..0000000
--- a/Help/release/dev/ExternalProject-BUILD_ALWAYS.rst
+++ /dev/null
@@ -1,6 +0,0 @@
-ExternalProject-BUILD_ALWAYS
-----------------------------
-
-* The :module:`ExternalProject` module ``ExternalProject_Add`` command
-  learned a new ``BUILD_ALWAYS`` option to cause the external project
-  build step to run every time the host project is built.
diff --git a/Help/release/dev/ExternalProject-no-download-progress.rst b/Help/release/dev/ExternalProject-no-download-progress.rst
deleted file mode 100644
index 41db55d..0000000
--- a/Help/release/dev/ExternalProject-no-download-progress.rst
+++ /dev/null
@@ -1,6 +0,0 @@
-ExternalProject-no-download-progress
-------------------------------------
-
-* The :module:`ExternalProject` module ``ExternalProject_Add`` command
-  learned a new ``DOWNLOAD_NO_PROGRESS`` option to disable progress
-  output while downloading the source tarball.
diff --git a/Help/release/dev/ExternalProject_exclude-from-all.rst b/Help/release/dev/ExternalProject_exclude-from-all.rst
deleted file mode 100644
index 1d62b3a..0000000
--- a/Help/release/dev/ExternalProject_exclude-from-all.rst
+++ /dev/null
@@ -1,11 +0,0 @@
-ExternalProject_exclude-from-all
---------------------------------
-
-* The :module:`ExternalProject` module ``ExternalProject_Add`` command
-  learned a new ``EXCLUDE_FROM_ALL`` option to cause the external
-  project target to have the :prop_tgt:`EXCLUDE_FROM_ALL` target
-  property set.
-
-* The :module:`ExternalProject` module ``ExternalProject_Add_Step`` command
-  learned a new ``EXCLUDE_FROM_MAIN`` option to cause the step to not be
-  a direct dependency of the main external project target.
diff --git a/Help/release/dev/FeatureSummary_combine_WHAT_values.rst b/Help/release/dev/FeatureSummary_combine_WHAT_values.rst
deleted file mode 100644
index 174ef15..0000000
--- a/Help/release/dev/FeatureSummary_combine_WHAT_values.rst
+++ /dev/null
@@ -1,6 +0,0 @@
-FeatureSummary_combine_WHAT_values
-----------------------------------
-
-* The :module:`FeatureSummary` module ``feature_summary`` API
-  learned to accept multiple values for the ``WHAT`` option and
-  combine them appropriately.
diff --git a/Help/release/dev/FindCUDA-cubin-fatbin.rst b/Help/release/dev/FindCUDA-cubin-fatbin.rst
deleted file mode 100644
index d44da8e..0000000
--- a/Help/release/dev/FindCUDA-cubin-fatbin.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-FindCUDA-cubin-fatbin
----------------------
-
-* The :module:`FindCUDA` module learned to support ``fatbin`` and ``cubin``
-  modules.
diff --git a/Help/release/dev/FindGTest-AUTO-SOURCES.rst b/Help/release/dev/FindGTest-AUTO-SOURCES.rst
deleted file mode 100644
index 17b2a1b..0000000
--- a/Help/release/dev/FindGTest-AUTO-SOURCES.rst
+++ /dev/null
@@ -1,7 +0,0 @@
-FindGTest-AUTO-SOURCES
-----------------------
-
-* The :module:`FindGTest` module ``gtest_add_tests`` macro learned
-  a new ``AUTO`` option to automatically read the :prop_tgt:`SOURCES`
-  target property of the test executable and scan the source files
-  for tests to be added.
diff --git a/Help/release/dev/FindHg-WC_INFO.rst b/Help/release/dev/FindHg-WC_INFO.rst
deleted file mode 100644
index 0caf2b3..0000000
--- a/Help/release/dev/FindHg-WC_INFO.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-FindHg-WC_INFO
---------------
-
-* The :module:`FindHg` module gained a new ``Hg_WC_INFO`` macro to
-  help run ``hg`` to extract information about a Mercurial work copy.
diff --git a/Help/release/dev/FindPkgConfig-PKG_CONFIG.rst b/Help/release/dev/FindPkgConfig-PKG_CONFIG.rst
deleted file mode 100644
index c0f6471..0000000
--- a/Help/release/dev/FindPkgConfig-PKG_CONFIG.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-FindPkgConfig-PKG_CONFIG
-------------------------
-
-* The :module:`FindPkgConfig` module learned to use the ``PKG_CONFIG``
-  environment variable value as the ``pkg-config`` executable, if set.
diff --git a/Help/release/dev/OpenWatcom.rst b/Help/release/dev/OpenWatcom.rst
deleted file mode 100644
index 63f6e8c..0000000
--- a/Help/release/dev/OpenWatcom.rst
+++ /dev/null
@@ -1,9 +0,0 @@
-OpenWatcom
-----------
-
-* Support for the Open Watcom compiler has been overhauled.
-  The :variable:`CMAKE_<LANG>_COMPILER_ID` is now ``OpenWatcom``,
-  and the :variable:`CMAKE_<LANG>_COMPILER_VERSION` now uses
-  the Open Watcom external version numbering.  The external
-  version numbers are lower than the internal version number
-  by 11.
diff --git a/Help/release/dev/UseSWIG-guess_module_name.rst b/Help/release/dev/UseSWIG-guess_module_name.rst
deleted file mode 100644
index c895046..0000000
--- a/Help/release/dev/UseSWIG-guess_module_name.rst
+++ /dev/null
@@ -1,6 +0,0 @@
-UseSWIG-guess_module_name
--------------------------
-
-* The :module:`UseSWIG` module learned to detect the module name
-  from ``.i`` source files if possible to avoid the need to set
-  the ``SWIG_MODULE_NAME`` source file property explicitly.
diff --git a/Help/release/dev/add-FindOpenCL.rst b/Help/release/dev/add-FindOpenCL.rst
deleted file mode 100644
index e1e30d1..0000000
--- a/Help/release/dev/add-FindOpenCL.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-add-FindOpenCL
---------------
-
-* The :module:`FindOpenCL` module was introduced.
diff --git a/Help/release/dev/add_custom_command-DEPENDS-genex.rst b/Help/release/dev/add_custom_command-DEPENDS-genex.rst
deleted file mode 100644
index 1e528e6..0000000
--- a/Help/release/dev/add_custom_command-DEPENDS-genex.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-add_custom_command-DEPENDS-genex
---------------------------------
-
-* The :command:`add_custom_command` command learned to interpret
-  :manual:`cmake-generator-expressions(7)` in arguments to ``DEPENDS``.
diff --git a/Help/release/dev/cmake-gui-capture-output.rst b/Help/release/dev/cmake-gui-capture-output.rst
deleted file mode 100644
index 40cd25e..0000000
--- a/Help/release/dev/cmake-gui-capture-output.rst
+++ /dev/null
@@ -1,6 +0,0 @@
-cmake-gui-capture-output
-------------------------
-
-* The :manual:`cmake-gui(1)` learned to capture output from child
-  processes started by the :command:`execute_process` command
-  and display it in the output window.
diff --git a/Help/release/dev/compile-language-features.rst b/Help/release/dev/compile-language-features.rst
deleted file mode 100644
index d10e22b..0000000
--- a/Help/release/dev/compile-language-features.rst
+++ /dev/null
@@ -1,28 +0,0 @@
-target-language-features
-------------------------
-
-* New :prop_tgt:`CXX_STANDARD` and :prop_tgt:`CXX_EXTENSIONS` target
-  properties may specify values which CMake uses to compute required
-  compile options such as ``-std=c++11`` or ``-std=gnu++11``. The
-  :variable:`CMAKE_CXX_STANDARD` and :variable:`CMAKE_CXX_EXTENSIONS`
-  variables may be set to initialize the target properties.
-
-* New :prop_tgt:`C_STANDARD` and :prop_tgt:`C_EXTENSIONS` target
-  properties may specify values which CMake uses to compute required
-  compile options such as ``-std=c11`` or ``-std=gnu11``. The
-  :variable:`CMAKE_C_STANDARD` and :variable:`CMAKE_C_EXTENSIONS`
-  variables may be set to initialize the target properties.
-
-* New :prop_tgt:`COMPILE_FEATURES` target property may contain a list
-  of features required to compile a target.  CMake uses this
-  information to ensure that the compiler in use is capable of building
-  the target, and to add any necessary compile flags to support language
-  features.
-
-* New :command:`target_compile_features` command allows populating the
-  :prop_tgt:`COMPILE_FEATURES` target property, just like any other
-  build variable.
-
-* New ``COMPILE_FEATURES``
-  :manual:`generator expression <cmake-generator-expressions(7)>` allows
-  setting build properties based on available compiler features.
diff --git a/Help/release/dev/cpack-deb-compression-types.rst b/Help/release/dev/cpack-deb-compression-types.rst
deleted file mode 100644
index a33e333..0000000
--- a/Help/release/dev/cpack-deb-compression-types.rst
+++ /dev/null
@@ -1,6 +0,0 @@
-cpack-deb-compression-types
----------------------------
-
-* The :module:`CPackDeb` module learned a new
-  :variable:`CPACK_DEBIAN_COMPRESSION_TYPE` variable to set the
-  tarball compression type.
diff --git a/Help/release/dev/ctest-coverage-extra.rst b/Help/release/dev/ctest-coverage-extra.rst
deleted file mode 100644
index 85d023b..0000000
--- a/Help/release/dev/ctest-coverage-extra.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-ctest-coverage-extra
---------------------
-
-* The :command:`ctest_coverage` command learned to read variable
-  ``CTEST_COVERAGE_EXTRA_FLAGS`` to set ``CoverageExtraFlags``.
diff --git a/Help/release/dev/ctest-intel-coverage.rst b/Help/release/dev/ctest-intel-coverage.rst
deleted file mode 100644
index 11455a5..0000000
--- a/Help/release/dev/ctest-intel-coverage.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-ctest-intel-coverage
---------------------
-
-* The :command:`ctest_coverage` command learned to support
-  Intel coverage files with the ``codecov`` tool.
diff --git a/Help/release/dev/custom-ninja-deptypes.rst b/Help/release/dev/custom-ninja-deptypes.rst
deleted file mode 100644
index 7750da8..0000000
--- a/Help/release/dev/custom-ninja-deptypes.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-custom-ninja-deptypes
----------------------
-
-* Add a `CMAKE_NINJA_DEPTYPE_<LANG>` variable so that compilers may set the
-  deptype for use in Ninja other than those CMake itself knows about.
diff --git a/Help/release/dev/delay-generator-toolset.rst b/Help/release/dev/delay-generator-toolset.rst
deleted file mode 100644
index 0512834..0000000
--- a/Help/release/dev/delay-generator-toolset.rst
+++ /dev/null
@@ -1,8 +0,0 @@
-delay-generator-toolset
------------------------
-
-* The :variable:`CMAKE_GENERATOR_TOOLSET` variable may now be
-  initialized in a toolchain file specified by the
-  :variable:`CMAKE_TOOLCHAIN_FILE` variable.  This is useful
-  when cross-compiling with the Xcode or Visual Studio
-  generators.
diff --git a/Help/release/dev/faster-parsers.rst b/Help/release/dev/faster-parsers.rst
deleted file mode 100644
index c2a8bfb..0000000
--- a/Help/release/dev/faster-parsers.rst
+++ /dev/null
@@ -1,6 +0,0 @@
-faster-parsers
---------------
-
-* The :manual:`cmake-language(7)` internal implementation of generator
-  expression and list expansion parsers have been optimized and shows
-  non-trivial speedup on large projects.
diff --git a/Help/release/dev/link-libraries-response-files.rst b/Help/release/dev/link-libraries-response-files.rst
deleted file mode 100644
index cecf7f6..0000000
--- a/Help/release/dev/link-libraries-response-files.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-link-libraries-response-files
------------------------------
-
-* The Makefile generators learned to use response files with GNU tools
-  on Windows to pass library directories and names to the linker.
diff --git a/Help/release/dev/module-WriteCompilerDetectionHeader.rst b/Help/release/dev/module-WriteCompilerDetectionHeader.rst
deleted file mode 100644
index 10e7b86..0000000
--- a/Help/release/dev/module-WriteCompilerDetectionHeader.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-module-WriteCompilerDetectionHeader
------------------------------------
-
-* The :module:`WriteCompilerDetectionHeader` module was added to allow
-  creation of a portable header file for compiler optional feature detection.
diff --git a/Help/release/dev/msvc-compiler-pdb-files.rst b/Help/release/dev/msvc-compiler-pdb-files.rst
deleted file mode 100644
index d06d202..0000000
--- a/Help/release/dev/msvc-compiler-pdb-files.rst
+++ /dev/null
@@ -1,10 +0,0 @@
-msvc-compiler-pdb-files
------------------------
-
-* New :prop_tgt:`COMPILE_PDB_NAME` and
-  :prop_tgt:`COMPILE_PDB_OUTPUT_DIRECTORY` target properties
-  were introduced to specify the MSVC compiler program database
-  file location (``cl /Fd``).  This complements the existing
-  :prop_tgt:`PDB_NAME` and :prop_tgt:`PDB_OUTPUT_DIRECTORY`
-  target properties that specify the linker program database
-  file location (``link /pdb``).
diff --git a/Help/release/dev/package-disable-registry.rst b/Help/release/dev/package-disable-registry.rst
deleted file mode 100644
index 1b23fde..0000000
--- a/Help/release/dev/package-disable-registry.rst
+++ /dev/null
@@ -1,11 +0,0 @@
-package-disable-registry
-------------------------
-
-* The :command:`export(PACKAGE)` command learned to check the
-  :variable:`CMAKE_EXPORT_NO_PACKAGE_REGISTRY` variable to skip
-  exporting the package.
-
-* The :command:`find_package` command learned to check the
-  :variable:`CMAKE_FIND_PACKAGE_NO_PACKAGE_REGISTRY` and
-  :variable:`CMAKE_FIND_PACKAGE_NO_SYSTEM_PACKAGE_REGISTRY`
-  variables to skip searching the package registries.
diff --git a/Help/release/dev/string-GENEX_STRIP.rst b/Help/release/dev/string-GENEX_STRIP.rst
deleted file mode 100644
index b5b1074..0000000
--- a/Help/release/dev/string-GENEX_STRIP.rst
+++ /dev/null
@@ -1,6 +0,0 @@
-string-GENEX_STRIP
-------------------
-
-* The :command:`string` command learned a new ``GENEX_STRIP`` subcommand
-  which removes
-  :manual:`generator expression <cmake-generator-expressions(7)>`.
diff --git a/Help/release/dev/target-INTERFACE_SOURCES.rst b/Help/release/dev/target-INTERFACE_SOURCES.rst
deleted file mode 100644
index 4e34943..0000000
--- a/Help/release/dev/target-INTERFACE_SOURCES.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-target-INTERFACE_SOURCES
-------------------------
-
-* A new :prop_tgt:`INTERFACE_SOURCES` target property was introduced. This is
-  consumed by dependent targets, which compile and link the listed sources.
diff --git a/Help/release/dev/target-SOURCES-genex.rst b/Help/release/dev/target-SOURCES-genex.rst
deleted file mode 100644
index 9a65101..0000000
--- a/Help/release/dev/target-SOURCES-genex.rst
+++ /dev/null
@@ -1,12 +0,0 @@
-target-SOURCES-genex
---------------------
-
-* The :prop_tgt:`SOURCES` target property now contains
-  :manual:`generator expression <cmake-generator-expressions(7)>`
-  such as ``TARGET_OBJECTS`` when read at configure time, if
-  policy :policy:`CMP0051` is ``NEW``.
-
-* The :prop_tgt:`SOURCES` target property now generally supports
-  :manual:`generator expression <cmake-generator-expressions(7)>`.  The
-  generator expressions may be used in the :command:`add_library` and
-  :command:`add_executable` commands.
diff --git a/Help/release/dev/target-SOURCES-write.rst b/Help/release/dev/target-SOURCES-write.rst
deleted file mode 100644
index a754a73..0000000
--- a/Help/release/dev/target-SOURCES-write.rst
+++ /dev/null
@@ -1,6 +0,0 @@
-target-SOURCES-write.rst
-------------------------
-
-* It is now possible to write and append to the :prop_tgt:`SOURCES` target
-  property.  The :variable:`CMAKE_DEBUG_TARGET_PROPERTIES` variable may be
-  used to trace the origin of sources.
diff --git a/Help/release/dev/target_sources-command.rst b/Help/release/dev/target_sources-command.rst
deleted file mode 100644
index abfb303..0000000
--- a/Help/release/dev/target_sources-command.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-target_sources-command
-----------------------
-
-* The :command:`target_sources` command was added to add to the
-  :prop_tgt:`SOURCES` target property.
diff --git a/Help/release/dev/variable_watch-no-allowed-access.rst b/Help/release/dev/variable_watch-no-allowed-access.rst
deleted file mode 100644
index ba7b4a5..0000000
--- a/Help/release/dev/variable_watch-no-allowed-access.rst
+++ /dev/null
@@ -1,8 +0,0 @@
-variable_watch-no-allowed-access
---------------------------------
-
-* Callbacks established by the :command:`variable_watch` command will no
-  longer receive the ``ALLOWED_UNKNOWN_READ_ACCESS`` access type when
-  the undocumented ``CMAKE_ALLOW_UNKNOWN_VARIABLE_READ_ACCESS`` variable is
-  set.  Uninitialized variable accesses will always be reported as
-  ``UNKNOWN_READ_ACCESS``.
diff --git a/Help/release/dev/xcode-file-type.rst b/Help/release/dev/xcode-file-type.rst
deleted file mode 100644
index 6f637f7..0000000
--- a/Help/release/dev/xcode-file-type.rst
+++ /dev/null
@@ -1,7 +0,0 @@
-xcode-file-type
----------------
-
-* The :generator:`Xcode` generator learned to check source
-  file properties  :prop_sf:`XCODE_EXPLICIT_FILE_TYPE` and
-  :prop_sf:`XCODE_LAST_KNOWN_FILE_TYPE` for a custom Xcode
-  file reference type.
diff --git a/Help/release/index.rst b/Help/release/index.rst
index 15ce065..616a582 100644
--- a/Help/release/index.rst
+++ b/Help/release/index.rst
@@ -5,12 +5,11 @@
   This file should include the adjacent "dev.txt" file
   in development versions but not in release versions.
 
-.. include:: dev.txt
-
 Releases
 ========
 
 .. toctree::
    :maxdepth: 1
 
+   3.1.0 <3.1.0>
    3.0.0 <3.0.0>
diff --git a/Help/variable/CMAKE_ANDROID_API.rst b/Help/variable/CMAKE_ANDROID_API.rst
new file mode 100644
index 0000000..c8264e0
--- /dev/null
+++ b/Help/variable/CMAKE_ANDROID_API.rst
@@ -0,0 +1,5 @@
+CMAKE_ANDROID_API
+-----------------
+
+Default value for the :prop_tgt:`ANDROID_API` target property.
+See that target property for additional information.
diff --git a/Help/variable/CMAKE_ANDROID_GUI.rst b/Help/variable/CMAKE_ANDROID_GUI.rst
new file mode 100644
index 0000000..1755375
--- /dev/null
+++ b/Help/variable/CMAKE_ANDROID_GUI.rst
@@ -0,0 +1,5 @@
+CMAKE_ANDROID_GUI
+-----------------
+
+Default value for the :prop_tgt:`ANDROID_GUI` target property of
+executables.  See that target property for additional information.
diff --git a/Help/variable/CMAKE_GENERATOR_PLATFORM.rst b/Help/variable/CMAKE_GENERATOR_PLATFORM.rst
new file mode 100644
index 0000000..5809b6a
--- /dev/null
+++ b/Help/variable/CMAKE_GENERATOR_PLATFORM.rst
@@ -0,0 +1,15 @@
+CMAKE_GENERATOR_PLATFORM
+------------------------
+
+Generator-specific target platform name specified by user.
+
+Some CMake generators support a target platform name to be given
+to the native build system to choose a compiler toolchain.
+If the user specifies a toolset name (e.g. via the cmake -A option)
+the value will be available in this variable.
+
+The value of this variable should never be modified by project code.
+A toolchain file specified by the :variable:`CMAKE_TOOLCHAIN_FILE`
+variable may initialize ``CMAKE_GENERATOR_PLATFORM``.  Once a given
+build tree has been initialized with a particular value for this
+variable, changing the value has undefined behavior.
diff --git a/Help/variable/CMAKE_INSTALL_MESSAGE.rst b/Help/variable/CMAKE_INSTALL_MESSAGE.rst
new file mode 100644
index 0000000..304df26
--- /dev/null
+++ b/Help/variable/CMAKE_INSTALL_MESSAGE.rst
@@ -0,0 +1,30 @@
+CMAKE_INSTALL_MESSAGE
+---------------------
+
+Specify verbosity of installation script code generated by the
+:command:`install` command (using the :command:`file(INSTALL)` command).
+For paths that are newly installed or updated, installation
+may print lines like::
+
+  -- Installing: /some/destination/path
+
+For paths that are already up to date, installation may print
+lines like::
+
+  -- Up-to-date: /some/destination/path
+
+The ``CMAKE_INSTALL_MESSAGE`` variable may be set to control
+which messages are printed:
+
+``ALWAYS``
+  Print both ``Installing`` and ``Up-to-date`` messages.
+
+``LAZY``
+  Print ``Installing`` but not ``Up-to-date`` messages.
+
+``NEVER``
+  Print neither ``Installing`` nor ``Up-to-date`` messages.
+
+Other values have undefined behavior and may not be diagnosed.
+
+If this variable is not set, the default behavior is ``ALWAYS``.
diff --git a/Help/variable/CMAKE_VS_NsightTegra_VERSION.rst b/Help/variable/CMAKE_VS_NsightTegra_VERSION.rst
new file mode 100644
index 0000000..386c3a9
--- /dev/null
+++ b/Help/variable/CMAKE_VS_NsightTegra_VERSION.rst
@@ -0,0 +1,7 @@
+CMAKE_VS_NsightTegra_VERSION
+----------------------------
+
+When using a Visual Studio generator with the
+:variable:`CMAKE_SYSTEM_NAME` variable set to ``Android``,
+this variable contains the version number of the
+installed NVIDIA Nsight Tegra Visual Studio Edition.
diff --git a/Help/variable/CMAKE_VS_PLATFORM_NAME.rst b/Help/variable/CMAKE_VS_PLATFORM_NAME.rst
new file mode 100644
index 0000000..c6f8d41
--- /dev/null
+++ b/Help/variable/CMAKE_VS_PLATFORM_NAME.rst
@@ -0,0 +1,7 @@
+CMAKE_VS_PLATFORM_NAME
+----------------------
+
+Visual Studio target platform name.
+
+VS 8 and above allow project files to specify a target platform.
+CMake provides the name of the chosen platform in this variable.
diff --git a/Help/variable/CMAKE_XCODE_ATTRIBUTE_an-attribute.rst b/Help/variable/CMAKE_XCODE_ATTRIBUTE_an-attribute.rst
new file mode 100644
index 0000000..096f64e
--- /dev/null
+++ b/Help/variable/CMAKE_XCODE_ATTRIBUTE_an-attribute.rst
@@ -0,0 +1,10 @@
+CMAKE_XCODE_ATTRIBUTE_<an-attribute>
+------------------------------------
+
+Set Xcode target attributes directly.
+
+Tell the Xcode generator to set '<an-attribute>' to a given value in
+the generated Xcode project.  Ignored on other generators.
+
+See the :prop_tgt:`XCODE_ATTRIBUTE_<an-attribute>` target property
+to set attributes on a specific target.
diff --git a/Help/variable/CTEST_MEMORYCHECK_SANITIZER_OPTIONS.rst b/Help/variable/CTEST_MEMORYCHECK_SANITIZER_OPTIONS.rst
new file mode 100644
index 0000000..2de5fb6
--- /dev/null
+++ b/Help/variable/CTEST_MEMORYCHECK_SANITIZER_OPTIONS.rst
@@ -0,0 +1,5 @@
+CTEST_MEMORYCHECK_SANITIZER_OPTIONS
+-----------------------------------
+
+Specify the CTest ``MemoryCheckSanitizerOptions`` setting
+in a :manual:`ctest(1)` dashboard client script.
diff --git a/Help/variable/CTEST_MEMORYCHECK_TYPE.rst b/Help/variable/CTEST_MEMORYCHECK_TYPE.rst
new file mode 100644
index 0000000..f1087c0
--- /dev/null
+++ b/Help/variable/CTEST_MEMORYCHECK_TYPE.rst
@@ -0,0 +1,7 @@
+CTEST_MEMORYCHECK_TYPE
+----------------------
+
+Specify the CTest ``MemoryCheckType`` setting
+in a :manual:`ctest(1)` dashboard client script.
+Valid values are Valgrind, Purify, BoundsChecker, and ThreadSanitizer,
+AddressSanitizer, MemorySanitizer, and UndefinedBehaviorSanitizer.
diff --git a/Help/variable/CTEST_UPDATE_VERSION_ONLY.rst b/Help/variable/CTEST_UPDATE_VERSION_ONLY.rst
new file mode 100644
index 0000000..e646e6e
--- /dev/null
+++ b/Help/variable/CTEST_UPDATE_VERSION_ONLY.rst
@@ -0,0 +1,5 @@
+CTEST_UPDATE_VERSION_ONLY
+-------------------------
+
+Specify the CTest ``UpdateVersionOnly`` setting
+in a :manual:`ctest(1)` dashboard client script.
diff --git a/Help/variable/MSVC14.rst b/Help/variable/MSVC14.rst
new file mode 100644
index 0000000..33c782b
--- /dev/null
+++ b/Help/variable/MSVC14.rst
@@ -0,0 +1,6 @@
+MSVC14
+------
+
+True when using Microsoft Visual C 14.0
+
+Set to true when the compiler is version 14.0 of Microsoft Visual C.
diff --git a/Help/variable/MSVC_VERSION.rst b/Help/variable/MSVC_VERSION.rst
index d74114e..ef3b0b5 100644
--- a/Help/variable/MSVC_VERSION.rst
+++ b/Help/variable/MSVC_VERSION.rst
@@ -3,9 +3,7 @@
 
 The version of Microsoft Visual C/C++ being used if any.
 
-Known version numbers are:
-
-::
+Known version numbers are::
 
   1200 = VS  6.0
   1300 = VS  7.0
@@ -15,3 +13,4 @@
   1600 = VS 10.0
   1700 = VS 11.0
   1800 = VS 12.0
+  1900 = VS 14.0
diff --git a/Help/variable/WINCE.rst b/Help/variable/WINCE.rst
new file mode 100644
index 0000000..54ff7de
--- /dev/null
+++ b/Help/variable/WINCE.rst
@@ -0,0 +1,5 @@
+WINCE
+-----
+
+True when the :variable:`CMAKE_SYSTEM_NAME` variable is set
+to ``WindowsCE``.
diff --git a/Help/variable/WINDOWS_PHONE.rst b/Help/variable/WINDOWS_PHONE.rst
new file mode 100644
index 0000000..61d91b0
--- /dev/null
+++ b/Help/variable/WINDOWS_PHONE.rst
@@ -0,0 +1,5 @@
+WINDOWS_PHONE
+-------------
+
+True when the :variable:`CMAKE_SYSTEM_NAME` variable is set
+to ``WindowsPhone``.
diff --git a/Help/variable/WINDOWS_STORE.rst b/Help/variable/WINDOWS_STORE.rst
new file mode 100644
index 0000000..dae3b53
--- /dev/null
+++ b/Help/variable/WINDOWS_STORE.rst
@@ -0,0 +1,5 @@
+WINDOWS_STORE
+-------------
+
+True when the :variable:`CMAKE_SYSTEM_NAME` variable is set
+to ``WindowsStore``.
diff --git a/Modules/BundleUtilities.cmake b/Modules/BundleUtilities.cmake
index 0c733fa..fee0a7c 100644
--- a/Modules/BundleUtilities.cmake
+++ b/Modules/BundleUtilities.cmake
@@ -19,6 +19,7 @@
 #    get_bundle_and_executable
 #    get_bundle_all_executables
 #    get_item_key
+#    get_item_rpaths
 #    clear_bundle_keys
 #    set_bundle_key_values
 #    get_bundle_keys
@@ -124,7 +125,7 @@
 # ::
 #
 #   SET_BUNDLE_KEY_VALUES(<keys_var> <context> <item> <exepath> <dirs>
-#                         <copyflag>)
+#                         <copyflag> [<rpaths>])
 #
 # Add a key to the list (if necessary) for the given item.  If added,
 # also set all the variables associated with that key.
@@ -237,6 +238,7 @@
     file(READ "${bundle}/Contents/Info.plist" info_plist)
     string(REPLACE ";" "\\;" info_plist "${info_plist}")
     string(REPLACE "\n" "${eol_char};" info_plist "${info_plist}")
+    string(REPLACE "\r" "${eol_char};" info_plist "${info_plist}")
 
     # Scan the lines for "<key>CFBundleExecutable</key>" - the line after that
     # is the name of the main executable.
@@ -377,7 +379,25 @@
 function(get_bundle_all_executables bundle exes_var)
   set(exes "")
 
-  file(GLOB_RECURSE file_list "${bundle}/*")
+  if(UNIX)
+    find_program(find_cmd "find")
+    mark_as_advanced(find_cmd)
+  endif()
+
+  # find command is much quicker than checking every file one by one on Unix
+  # which can take long time for large bundles, and since anyway we expect
+  # executable to have execute flag set we can narrow the list much quicker.
+  if(find_cmd)
+    execute_process(COMMAND "${find_cmd}" "${bundle}"
+      -type f \( -perm -0100 -o -perm -0010 -o -perm -0001 \)
+      OUTPUT_VARIABLE file_list
+      OUTPUT_STRIP_TRAILING_WHITESPACE
+      )
+    string(REPLACE "\n" ";" file_list "${file_list}")
+  else()
+    file(GLOB_RECURSE file_list "${bundle}/*")
+  endif()
+
   foreach(f ${file_list})
     is_file_executable("${f}" is_executable)
     if(is_executable)
@@ -389,6 +409,29 @@
 endfunction()
 
 
+function(get_item_rpaths item rpaths_var)
+  if(APPLE)
+    find_program(otool_cmd "otool")
+    mark_as_advanced(otool_cmd)
+  endif()
+
+  if(otool_cmd)
+    execute_process(
+      COMMAND "${otool_cmd}" -l "${item}"
+      OUTPUT_VARIABLE load_cmds_ov
+      )
+    string(REGEX REPLACE "[^\n]+cmd LC_RPATH\n[^\n]+\n[^\n]+path ([^\n]+) \\(offset[^\n]+\n" "rpath \\1\n" load_cmds_ov "${load_cmds_ov}")
+    string(REGEX MATCHALL "rpath [^\n]+" load_cmds_ov "${load_cmds_ov}")
+    string(REGEX REPLACE "rpath " "" load_cmds_ov "${load_cmds_ov}")
+    if(load_cmds_ov)
+      gp_append_unique(${rpaths_var} "${load_cmds_ov}")
+    endif()
+  endif()
+
+  set(${rpaths_var} ${${rpaths_var}} PARENT_SCOPE)
+endfunction()
+
+
 function(get_item_key item key_var)
   get_filename_component(item_name "${item}" NAME)
   if(WIN32)
@@ -407,12 +450,14 @@
     set(${key}_EMBEDDED_ITEM PARENT_SCOPE)
     set(${key}_RESOLVED_EMBEDDED_ITEM PARENT_SCOPE)
     set(${key}_COPYFLAG PARENT_SCOPE)
+    set(${key}_RPATHS PARENT_SCOPE)
   endforeach()
   set(${keys_var} PARENT_SCOPE)
 endfunction()
 
 
 function(set_bundle_key_values keys_var context item exepath dirs copyflag)
+  set(rpaths "${ARGV6}")
   get_filename_component(item_name "${item}" NAME)
 
   get_item_key("${item}" key)
@@ -422,10 +467,12 @@
   list(LENGTH ${keys_var} length_after)
 
   if(NOT length_before EQUAL length_after)
-    gp_resolve_item("${context}" "${item}" "${exepath}" "${dirs}" resolved_item)
+    gp_resolve_item("${context}" "${item}" "${exepath}" "${dirs}" resolved_item "${rpaths}")
 
     gp_item_default_embedded_path("${item}" default_embedded_path)
 
+    get_item_rpaths("${resolved_item}" item_rpaths)
+
     if(item MATCHES "[^/]+\\.framework/")
       # For frameworks, construct the name under the embedded path from the
       # opening "${item_name}.framework/" to the closing "/${item_name}":
@@ -461,6 +508,8 @@
     set(${key}_EMBEDDED_ITEM "${embedded_item}" PARENT_SCOPE)
     set(${key}_RESOLVED_EMBEDDED_ITEM "${resolved_embedded_item}" PARENT_SCOPE)
     set(${key}_COPYFLAG "${copyflag}" PARENT_SCOPE)
+    set(${key}_RPATHS "${item_rpaths}" PARENT_SCOPE)
+    set(${key}_RDEP_RPATHS "${rpaths}" PARENT_SCOPE)
   else()
     #message("warning: item key '${key}' already in the list, subsequent references assumed identical to first")
   endif()
@@ -481,18 +530,27 @@
     #
     get_bundle_all_executables("${bundle}" exes)
 
+    # Set keys for main executable first:
+    #
+    set_bundle_key_values(${keys_var} "${executable}" "${executable}" "${exepath}" "${dirs}" 0)
+
+    # Get rpaths specified by main executable:
+    #
+    get_item_key("${executable}" executable_key)
+    set(main_rpaths "${${executable_key}_RPATHS}")
+
     # For each extra lib, accumulate a key as well and then also accumulate
     # any of its prerequisites. (Extra libs are typically dynamically loaded
     # plugins: libraries that are prerequisites for full runtime functionality
     # but that do not show up in otool -L output...)
     #
     foreach(lib ${libs})
-      set_bundle_key_values(${keys_var} "${lib}" "${lib}" "${exepath}" "${dirs}" 0)
+      set_bundle_key_values(${keys_var} "${lib}" "${lib}" "${exepath}" "${dirs}" 0 "${main_rpaths}")
 
       set(prereqs "")
-      get_prerequisites("${lib}" prereqs 1 1 "${exepath}" "${dirs}")
+      get_prerequisites("${lib}" prereqs 1 1 "${exepath}" "${dirs}" "${main_rpaths}")
       foreach(pr ${prereqs})
-        set_bundle_key_values(${keys_var} "${lib}" "${pr}" "${exepath}" "${dirs}" 1)
+        set_bundle_key_values(${keys_var} "${lib}" "${pr}" "${exepath}" "${dirs}" 1 "${main_rpaths}")
       endforeach()
     endforeach()
 
@@ -501,16 +559,27 @@
     # binaries in the bundle have been analyzed.
     #
     foreach(exe ${exes})
-      # Add the exe itself to the keys:
+      # Main executable is scanned first above:
       #
-      set_bundle_key_values(${keys_var} "${exe}" "${exe}" "${exepath}" "${dirs}" 0)
+      if(NOT "${exe}" STREQUAL "${executable}")
+        # Add the exe itself to the keys:
+        #
+        set_bundle_key_values(${keys_var} "${exe}" "${exe}" "${exepath}" "${dirs}" 0 "${main_rpaths}")
+
+        # Get rpaths specified by executable:
+        #
+        get_item_key("${exe}" exe_key)
+        set(exe_rpaths "${main_rpaths}" "${${exe_key}_RPATHS}")
+      else()
+        set(exe_rpaths "${main_rpaths}")
+      endif()
 
       # Add each prerequisite to the keys:
       #
       set(prereqs "")
-      get_prerequisites("${exe}" prereqs 1 1 "${exepath}" "${dirs}")
+      get_prerequisites("${exe}" prereqs 1 1 "${exepath}" "${dirs}" "${exe_rpaths}")
       foreach(pr ${prereqs})
-        set_bundle_key_values(${keys_var} "${exe}" "${pr}" "${exepath}" "${dirs}" 1)
+        set_bundle_key_values(${keys_var} "${exe}" "${pr}" "${exepath}" "${dirs}" 1 "${exe_rpaths}")
       endforeach()
     endforeach()
 
@@ -524,6 +593,8 @@
       set(${key}_EMBEDDED_ITEM "${${key}_EMBEDDED_ITEM}" PARENT_SCOPE)
       set(${key}_RESOLVED_EMBEDDED_ITEM "${${key}_RESOLVED_EMBEDDED_ITEM}" PARENT_SCOPE)
       set(${key}_COPYFLAG "${${key}_COPYFLAG}" PARENT_SCOPE)
+      set(${key}_RPATHS "${${key}_RPATHS}" PARENT_SCOPE)
+      set(${key}_RDEP_RPATHS "${${key}_RDEP_RPATHS}" PARENT_SCOPE)
     endforeach()
   endif()
 endfunction()
@@ -579,12 +650,45 @@
       execute_process(COMMAND ${CMAKE_COMMAND} -E copy "${resolved_item}" "${resolved_embedded_item}")
 
       # Plus Resources, if they exist:
-      string(REGEX REPLACE "^(.*)/[^/]+/[^/]+/[^/]+$" "\\1/Resources" resolved_resources "${resolved_item}")
-      string(REGEX REPLACE "^(.*)/[^/]+/[^/]+/[^/]+$" "\\1/Resources" resolved_embedded_resources "${resolved_embedded_item}")
+      string(REGEX REPLACE "^(.*)/[^/]+$" "\\1/Resources" resolved_resources "${resolved_item}")
+      string(REGEX REPLACE "^(.*)/[^/]+$" "\\1/Resources" resolved_embedded_resources "${resolved_embedded_item}")
       if(EXISTS "${resolved_resources}")
         #message(STATUS "copying COMMAND ${CMAKE_COMMAND} -E copy_directory '${resolved_resources}' '${resolved_embedded_resources}'")
         execute_process(COMMAND ${CMAKE_COMMAND} -E copy_directory "${resolved_resources}" "${resolved_embedded_resources}")
       endif()
+
+      # Some frameworks e.g. Qt put Info.plist in wrong place, so when it is
+      # missing in resources, copy it from other well known incorrect locations:
+      if(NOT EXISTS "${resolved_resources}/Info.plist")
+        # Check for Contents/Info.plist in framework root (older Qt SDK):
+        string(REGEX REPLACE "^(.*)/[^/]+/[^/]+/[^/]+$" "\\1/Contents/Info.plist" resolved_info_plist "${resolved_item}")
+        string(REGEX REPLACE "^(.*)/[^/]+$" "\\1/Resources/Info.plist" resolved_embedded_info_plist "${resolved_embedded_item}")
+        if(EXISTS "${resolved_info_plist}")
+          #message(STATUS "copying COMMAND ${CMAKE_COMMAND} -E copy_directory '${resolved_info_plist}' '${resolved_embedded_info_plist}'")
+          execute_process(COMMAND ${CMAKE_COMMAND} -E copy "${resolved_info_plist}" "${resolved_embedded_info_plist}")
+        endif()
+      endif()
+
+      # Check if framework is versioned and fix it layout
+      string(REGEX REPLACE "^.*/([^/]+)/[^/]+$" "\\1" resolved_embedded_version "${resolved_embedded_item}")
+      string(REGEX REPLACE "^(.*)/[^/]+/[^/]+$" "\\1" resolved_embedded_versions "${resolved_embedded_item}")
+      string(REGEX REPLACE "^.*/([^/]+)/[^/]+/[^/]+$" "\\1" resolved_embedded_versions_basename "${resolved_embedded_item}")
+      if(resolved_embedded_versions_basename STREQUAL "Versions")
+        # Ensure Current symlink points to the framework version
+        if(NOT EXISTS "${resolved_embedded_versions}/Current")
+          execute_process(COMMAND ${CMAKE_COMMAND} -E create_symlink "${resolved_embedded_version}" "${resolved_embedded_versions}/Current")
+        endif()
+        # Restore symlinks in framework root pointing to current framework
+        # binary and resources:
+        string(REGEX REPLACE "^(.*)/[^/]+/[^/]+/[^/]+$" "\\1" resolved_embedded_root "${resolved_embedded_item}")
+        string(REGEX REPLACE "^.*/([^/]+)$" "\\1" resolved_embedded_item_basename "${resolved_embedded_item}")
+        if(NOT EXISTS "${resolved_embedded_root}/${resolved_embedded_item_basename}")
+          execute_process(COMMAND ${CMAKE_COMMAND} -E create_symlink "Versions/Current/${resolved_embedded_item_basename}" "${resolved_embedded_root}/${resolved_embedded_item_basename}")
+        endif()
+        if(NOT EXISTS "${resolved_embedded_root}/Resources")
+          execute_process(COMMAND ${CMAKE_COMMAND} -E create_symlink "Versions/Current/Resources" "${resolved_embedded_root}/Resources")
+        endif()
+      endif()
     endif()
     if(UNIX AND NOT APPLE)
       file(RPATH_REMOVE FILE "${resolved_embedded_item}")
@@ -629,8 +733,10 @@
     message(FATAL_ERROR "cannot fixup an item that is not in the bundle...")
   endif()
 
+  set(rpaths "${${ikey}_RPATHS}" "${${ikey}_RDEP_RPATHS}")
+
   set(prereqs "")
-  get_prerequisites("${resolved_embedded_item}" prereqs 1 0 "${exepath}" "${dirs}")
+  get_prerequisites("${resolved_embedded_item}" prereqs 1 0 "${exepath}" "${dirs}" "${rpaths}")
 
   set(changes "")
 
@@ -650,12 +756,28 @@
     execute_process(COMMAND chmod u+w "${resolved_embedded_item}")
   endif()
 
+  # Only if install_name_tool supports -delete_rpath:
+  #
+  execute_process(COMMAND install_name_tool
+    OUTPUT_VARIABLE install_name_tool_usage
+    ERROR_VARIABLE  install_name_tool_usage
+    )
+  if(install_name_tool_usage MATCHES ".*-delete_rpath.*")
+    foreach(rpath ${${ikey}_RPATHS})
+      set(changes ${changes} -delete_rpath "${rpath}")
+    endforeach()
+  endif()
+
+  if(${ikey}_EMBEDDED_ITEM)
+    set(changes ${changes} -id "${${ikey}_EMBEDDED_ITEM}")
+  endif()
+
   # Change this item's id and all of its references in one call
   # to install_name_tool:
   #
-  execute_process(COMMAND install_name_tool
-    ${changes} -id "${${ikey}_EMBEDDED_ITEM}" "${resolved_embedded_item}"
-  )
+  if(changes)
+    execute_process(COMMAND install_name_tool ${changes} "${resolved_embedded_item}")
+  endif()
 endfunction()
 
 
@@ -746,10 +868,8 @@
 
   get_bundle_main_executable("${bundle}" main_bundle_exe)
 
-  file(GLOB_RECURSE file_list "${bundle}/*")
+  get_bundle_all_executables("${bundle}" file_list)
   foreach(f ${file_list})
-    is_file_executable("${f}" is_executable)
-    if(is_executable)
       get_filename_component(exepath "${f}" PATH)
       math(EXPR count "${count} + 1")
 
@@ -788,7 +908,6 @@
         set(result 0)
         set(info ${info} "external prerequisites found:\nf='${f}'\nexternal_prereqs='${external_prereqs}'\n")
       endif()
-    endif()
   endforeach()
 
   if(result)
diff --git a/Modules/CMakeASMInformation.cmake b/Modules/CMakeASMInformation.cmake
index dce1624..62ef972 100644
--- a/Modules/CMakeASMInformation.cmake
+++ b/Modules/CMakeASMInformation.cmake
@@ -50,6 +50,24 @@
   include(Platform/${CMAKE_SYSTEM_NAME}-${CMAKE_BASE_NAME} OPTIONAL)
 endif()
 
+# This should be included before the _INIT variables are
+# used to initialize the cache.  Since the rule variables
+# have if blocks on them, users can still define them here.
+# But, it should still be after the platform file so changes can
+# be made to those values.
+
+if(CMAKE_USER_MAKE_RULES_OVERRIDE)
+  # Save the full path of the file so try_compile can use it.
+  include(${CMAKE_USER_MAKE_RULES_OVERRIDE} RESULT_VARIABLE _override)
+  set(CMAKE_USER_MAKE_RULES_OVERRIDE "${_override}")
+endif()
+
+if(CMAKE_USER_MAKE_RULES_OVERRIDE_ASM)
+  # Save the full path of the file so try_compile can use it.
+  include(${CMAKE_USER_MAKE_RULES_OVERRIDE_ASM} RESULT_VARIABLE _override)
+  set(CMAKE_USER_MAKE_RULES_OVERRIDE_ASM "${_override}")
+endif()
+
 # Set default assembler file extensions:
 if(NOT CMAKE_ASM${ASM_DIALECT}_SOURCE_FILE_EXTENSIONS)
   set(CMAKE_ASM${ASM_DIALECT}_SOURCE_FILE_EXTENSIONS s;S;asm)
diff --git a/Modules/CMakeASM_MASMInformation.cmake b/Modules/CMakeASM_MASMInformation.cmake
index eb105ab..972883c 100644
--- a/Modules/CMakeASM_MASMInformation.cmake
+++ b/Modules/CMakeASM_MASMInformation.cmake
@@ -18,7 +18,7 @@
 
 set(CMAKE_ASM${ASM_DIALECT}_SOURCE_FILE_EXTENSIONS asm)
 
-set(CMAKE_ASM${ASM_DIALECT}_COMPILE_OBJECT "<CMAKE_ASM${ASM_DIALECT}_COMPILER> <FLAGS> /c  /Fo <OBJECT> <SOURCE>")
+set(CMAKE_ASM${ASM_DIALECT}_COMPILE_OBJECT "<CMAKE_ASM${ASM_DIALECT}_COMPILER> <DEFINES> <FLAGS> /c  /Fo <OBJECT> <SOURCE>")
 
 include(CMakeASMInformation)
 set(ASM_DIALECT)
diff --git a/Modules/CMakeCheckCompilerFlagCommonPatterns.cmake b/Modules/CMakeCheckCompilerFlagCommonPatterns.cmake
index 9d8ba9e..19b2bbc 100644
--- a/Modules/CMakeCheckCompilerFlagCommonPatterns.cmake
+++ b/Modules/CMakeCheckCompilerFlagCommonPatterns.cmake
@@ -28,14 +28,16 @@
      FAIL_REGEX "option.*not supported"                     # Intel
      FAIL_REGEX "invalid argument .*option"                 # Intel
      FAIL_REGEX "ignoring option .*argument required"       # Intel
+     FAIL_REGEX "ignoring option .*argument is of wrong type" # Intel
      FAIL_REGEX "[Uu]nknown option"                         # HP
      FAIL_REGEX "[Ww]arning: [Oo]ption"                     # SunPro
      FAIL_REGEX "command option .* is not recognized"       # XL
      FAIL_REGEX "command option .* contains an incorrect subargument" # XL
-     FAIL_REGEX "not supported in this configuration; ignored"       # AIX
+     FAIL_REGEX "not supported in this configuration. ignored"       # AIX
      FAIL_REGEX "File with unknown suffix passed to linker" # PGI
      FAIL_REGEX "WARNING: unknown flag:"                    # Open64
      FAIL_REGEX "Incorrect command line option:"            # Borland
      FAIL_REGEX "Warning: illegal option"                   # SunStudio 12
+     FAIL_REGEX "[Ww]arning: Invalid suboption"             # Fujitsu
    )
 endmacro ()
diff --git a/Modules/CMakeCompilerIdDetection.cmake b/Modules/CMakeCompilerIdDetection.cmake
index d8a0d67..19bcbcc 100644
--- a/Modules/CMakeCompilerIdDetection.cmake
+++ b/Modules/CMakeCompilerIdDetection.cmake
@@ -17,6 +17,7 @@
   get_filename_component(name ${file} NAME_WE)
   string(REGEX REPLACE "-.*" "" CompilerId ${name})
   set(_compiler_id_version_compute_${CompilerId} ${_compiler_id_version_compute} PARENT_SCOPE)
+  set(_compiler_id_simulate_${CompilerId} ${_compiler_id_simulate} PARENT_SCOPE)
   set(_compiler_id_pp_test_${CompilerId} ${_compiler_id_pp_test} PARENT_SCOPE)
 endfunction()
 
@@ -60,8 +61,6 @@
     list(APPEND ordered_compilers
       Intel
       PathScale
-      AppleClang
-      Clang
       Embarcadero
       Borland
       Watcom
@@ -75,6 +74,7 @@
       PGI
       Cray
       TI
+      Fujitsu
     )
     if (lang STREQUAL C)
       list(APPEND ordered_compilers
@@ -83,6 +83,8 @@
     endif()
     list(APPEND ordered_compilers
       SCO
+      AppleClang
+      Clang
       GNU
       MSVC
       ADSP
@@ -114,7 +116,9 @@
       endif()
       set(id_content "${pp_if} ${_compiler_id_pp_test_${Id}}\n")
       if (CID_ID_STRING)
-        set(id_content "${id_content}# define ${CID_PREFIX}COMPILER_ID \"${Id}\"")
+        set(PREFIX ${CID_PREFIX})
+        string(CONFIGURE "${_compiler_id_simulate_${Id}}" SIMULATE_BLOCK @ONLY)
+        set(id_content "${id_content}# define ${CID_PREFIX}COMPILER_ID \"${Id}\"${SIMULATE_BLOCK}")
       endif()
       if (CID_ID_DEFINE)
         set(id_content "${id_content}# undef ${CID_PREFIX}COMPILER_IS_${Id}\n")
@@ -122,6 +126,8 @@
       endif()
       if (CID_VERSION_STRINGS)
         set(PREFIX ${CID_PREFIX})
+        set(MACRO_DEC DEC)
+        set(MACRO_HEX HEX)
         string(CONFIGURE "${_compiler_id_version_compute_${Id}}" VERSION_BLOCK @ONLY)
         set(id_content "${id_content}${VERSION_BLOCK}\n")
       endif()
diff --git a/Modules/CMakeDetermineASM_MASMCompiler.cmake b/Modules/CMakeDetermineASM_MASMCompiler.cmake
index 665a65c..142ef95 100644
--- a/Modules/CMakeDetermineASM_MASMCompiler.cmake
+++ b/Modules/CMakeDetermineASM_MASMCompiler.cmake
@@ -17,7 +17,8 @@
 set(ASM_DIALECT "_MASM")
 
 # if we are using the 64bit cl compiler, assume we also want the 64bit assembler
-if(CMAKE_CL_64)
+if(";${CMAKE_VS_PLATFORM_NAME};${MSVC_C_ARCHITECTURE_ID};${MSVC_CXX_ARCHITECTURE_ID};"
+    MATCHES ";(Win64|Itanium|x64|IA64);")
    set(CMAKE_ASM${ASM_DIALECT}_COMPILER_INIT ml64)
 else()
    set(CMAKE_ASM${ASM_DIALECT}_COMPILER_INIT ml)
diff --git a/Modules/CMakeDetermineCCompiler.cmake b/Modules/CMakeDetermineCCompiler.cmake
index 3847b75..6b425c6 100644
--- a/Modules/CMakeDetermineCCompiler.cmake
+++ b/Modules/CMakeDetermineCCompiler.cmake
@@ -136,7 +136,9 @@
     if (COMPILER_BASENAME MATCHES "^(.+-)(clang|g?cc)(-[0-9]+\\.[0-9]+\\.[0-9]+)?(\\.exe)?$")
       set(_CMAKE_TOOLCHAIN_PREFIX ${CMAKE_MATCH_1})
     elseif("${CMAKE_C_COMPILER_ID}" MATCHES "Clang")
-      set(_CMAKE_TOOLCHAIN_PREFIX ${CMAKE_C_COMPILER_TARGET}-)
+      if(CMAKE_C_COMPILER_TARGET)
+        set(_CMAKE_TOOLCHAIN_PREFIX ${CMAKE_C_COMPILER_TARGET}-)
+      endif()
     elseif(COMPILER_BASENAME MATCHES "qcc(\\.exe)?$")
       if(CMAKE_C_COMPILER_TARGET MATCHES "gcc_nto([^_le]+)(le)?")
         set(_CMAKE_TOOLCHAIN_PREFIX nto${CMAKE_MATCH_1}-)
diff --git a/Modules/CMakeDetermineCXXCompiler.cmake b/Modules/CMakeDetermineCXXCompiler.cmake
index e6a9d9a..893c454 100644
--- a/Modules/CMakeDetermineCXXCompiler.cmake
+++ b/Modules/CMakeDetermineCXXCompiler.cmake
@@ -133,7 +133,9 @@
     if (COMPILER_BASENAME MATCHES "^(.+-)(clan)?[gc]\\+\\+(-[0-9]+\\.[0-9]+\\.[0-9]+)?(\\.exe)?$")
       set(_CMAKE_TOOLCHAIN_PREFIX ${CMAKE_MATCH_1})
     elseif("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang")
-      set(_CMAKE_TOOLCHAIN_PREFIX ${CMAKE_CXX_COMPILER_TARGET}-)
+      if(CMAKE_CXX_COMPILER_TARGET)
+        set(_CMAKE_TOOLCHAIN_PREFIX ${CMAKE_CXX_COMPILER_TARGET}-)
+      endif()
     elseif(COMPILER_BASENAME MATCHES "QCC(\\.exe)?$")
       if(CMAKE_CXX_COMPILER_TARGET MATCHES "gcc_nto([^_le]+)(le)?")
         set(_CMAKE_TOOLCHAIN_PREFIX nto${CMAKE_MATCH_1}-)
diff --git a/Modules/CMakeDetermineCompiler.cmake b/Modules/CMakeDetermineCompiler.cmake
index cd0f8b8..0ab3af6 100644
--- a/Modules/CMakeDetermineCompiler.cmake
+++ b/Modules/CMakeDetermineCompiler.cmake
@@ -65,7 +65,7 @@
   endif()
   find_program(CMAKE_${lang}_COMPILER NAMES ${CMAKE_${lang}_COMPILER_LIST} DOC "${lang} compiler")
   if(CMAKE_${lang}_COMPILER_INIT AND NOT CMAKE_${lang}_COMPILER)
-    set(CMAKE_${lang}_COMPILER "${CMAKE_${lang}_COMPILER_INIT}" CACHE FILEPATH "${lang} compiler" FORCE)
+    set_property(CACHE CMAKE_${lang}_COMPILER PROPERTY VALUE "${CMAKE_${lang}_COMPILER_INIT}")
   endif()
   unset(_${lang}_COMPILER_HINTS)
   unset(_languages)
diff --git a/Modules/CMakeDetermineCompilerABI.cmake b/Modules/CMakeDetermineCompilerABI.cmake
index 8595b97..4bc42dd 100644
--- a/Modules/CMakeDetermineCompilerABI.cmake
+++ b/Modules/CMakeDetermineCompilerABI.cmake
@@ -28,13 +28,15 @@
     if(DEFINED CMAKE_${lang}_VERBOSE_FLAG)
       set(CMAKE_FLAGS "-DCMAKE_EXE_LINKER_FLAGS=${CMAKE_${lang}_VERBOSE_FLAG}")
     endif()
+    if(NOT "x${CMAKE_${lang}_COMPILER_ID}" STREQUAL "xMSVC")
+      # Avoid adding our own platform standard libraries for compilers
+      # from which we might detect implicit link libraries.
+      list(APPEND CMAKE_FLAGS "-DCMAKE_${lang}_STANDARD_LIBRARIES=")
+    endif()
     try_compile(CMAKE_${lang}_ABI_COMPILED
       ${CMAKE_BINARY_DIR} ${src}
-      CMAKE_FLAGS "${CMAKE_FLAGS}"
-                  "-DCMAKE_${lang}_STANDARD_LIBRARIES="
-                  # We need ignore these warnings because some platforms need
-                  # CMAKE_${lang}_STANDARD_LIBRARIES to link properly and we
-                  # don't care when we are just determining the ABI.
+      CMAKE_FLAGS ${CMAKE_FLAGS}
+                  # Ignore unused flags when we are just determining the ABI.
                   "--no-warn-unused-cli"
       OUTPUT_VARIABLE OUTPUT
       COPY_FILE "${BIN}"
@@ -50,7 +52,7 @@
       message(STATUS "Detecting ${lang} compiler ABI info - done")
       file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeOutput.log
         "Detecting ${lang} compiler ABI info compiled with the following output:\n${OUTPUT}\n\n")
-      file(STRINGS "${BIN}" ABI_STRINGS LIMIT_COUNT 2 REGEX "INFO:[^[]*\\[")
+      file(STRINGS "${BIN}" ABI_STRINGS LIMIT_COUNT 2 REGEX "INFO:[A-Za-z0-9_]+\\[[^]]*\\]")
       foreach(info ${ABI_STRINGS})
         if("${info}" MATCHES "INFO:sizeof_dptr\\[0*([^]]*)\\]")
           set(ABI_SIZEOF_DPTR "${CMAKE_MATCH_1}")
diff --git a/Modules/CMakeDetermineCompilerId.cmake b/Modules/CMakeDetermineCompilerId.cmake
index 025d296..613f4b3 100644
--- a/Modules/CMakeDetermineCompilerId.cmake
+++ b/Modules/CMakeDetermineCompilerId.cmake
@@ -142,7 +142,17 @@
     set(id_platform ${CMAKE_VS_PLATFORM_NAME})
     set(id_lang "${lang}")
     set(id_cl cl.exe)
-    if(lang STREQUAL Fortran)
+    if(CMAKE_VS_PLATFORM_NAME STREQUAL "Tegra-Android")
+      set(v NsightTegra)
+      set(ext vcxproj)
+      if(lang STREQUAL CXX)
+        set(id_gcc g++)
+        set(id_clang clang++)
+      else()
+        set(id_gcc gcc)
+        set(id_clang clang)
+      endif()
+    elseif(lang STREQUAL Fortran)
       set(v Intel)
       set(ext vfproj)
       set(id_cl ifort.exe)
@@ -161,13 +171,34 @@
       set(id_platform ia64)
     endif()
     if(CMAKE_VS_PLATFORM_TOOLSET)
-      set(id_toolset "<PlatformToolset>${CMAKE_VS_PLATFORM_TOOLSET}</PlatformToolset>")
-      if(CMAKE_VS_PLATFORM_TOOLSET MATCHES "Intel")
-        set(id_cl icl.exe)
+      if(CMAKE_VS_PLATFORM_NAME STREQUAL "Tegra-Android")
+        set(id_toolset "<NdkToolchainVersion>${CMAKE_VS_PLATFORM_TOOLSET}</NdkToolchainVersion>")
+      else()
+        set(id_toolset "<PlatformToolset>${CMAKE_VS_PLATFORM_TOOLSET}</PlatformToolset>")
+        if(CMAKE_VS_PLATFORM_TOOLSET MATCHES "Intel")
+          set(id_cl icl.exe)
+        endif()
       endif()
     else()
       set(id_toolset "")
     endif()
+    if(CMAKE_SYSTEM_NAME STREQUAL "WindowsPhone")
+      set(id_system "<ApplicationType>Windows Phone</ApplicationType>")
+    elseif(CMAKE_SYSTEM_NAME STREQUAL "WindowsStore")
+      set(id_system "<ApplicationType>Windows Store</ApplicationType>")
+    else()
+      set(id_system "")
+    endif()
+    if(id_system AND CMAKE_SYSTEM_VERSION)
+      set(id_system_version "<ApplicationTypeRevision>${CMAKE_SYSTEM_VERSION}</ApplicationTypeRevision>")
+    else()
+      set(id_system_version "")
+    endif()
+    if(id_platform STREQUAL ARM)
+      set(id_WindowsSDKDesktopARMSupport "<WindowsSDKDesktopARMSupport>true</WindowsSDKDesktopARMSupport>")
+    else()
+      set(id_WindowsSDKDesktopARMSupport "")
+    endif()
     if(CMAKE_VS_WINCE_VERSION)
       set(id_entrypoint "mainACRTStartup")
       if("${vs_version}" VERSION_LESS 9)
@@ -230,11 +261,20 @@
     else()
       set(id_deployment_target "")
     endif()
+    set(id_product_type "com.apple.product-type.tool")
     if(CMAKE_OSX_SYSROOT)
       set(id_sdkroot "SDKROOT = \"${CMAKE_OSX_SYSROOT}\";")
+      if(CMAKE_OSX_SYSROOT MATCHES "(^|/)[Ii][Pp][Hh][Oo][Nn][Ee]")
+        set(id_product_type "com.apple.product-type.bundle.unit-test")
+      endif()
     else()
       set(id_sdkroot "")
     endif()
+    if(CMAKE_XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY)
+      set(id_code_sign_identity "CODE_SIGN_IDENTITY = \"${CMAKE_XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY}\";")
+    else()
+      set(id_code_sign_identity "")
+    endif()
     if(NOT ${XCODE_VERSION} VERSION_LESS 3)
       set(v 3)
       set(ext xcodeproj)
@@ -267,7 +307,7 @@
     #      ...
     #      /path/to/cc ...CompilerId${lang}/...
     # to extract the compiler front-end for the language.
-    if("${CMAKE_${lang}_COMPILER_ID_OUTPUT}" MATCHES "\nLd[^\n]*(\n[ \t]+[^\n]*)*\n[ \t]+([^ \t\r\n]+)[^\r\n]*-o[^\r\n]*CompilerId${lang}/(\\./)?CompilerId${lang}[ \t\n\\\"]")
+    if("${CMAKE_${lang}_COMPILER_ID_OUTPUT}" MATCHES "\nLd[^\n]*(\n[ \t]+[^\n]*)*\n[ \t]+([^ \t\r\n]+)[^\r\n]*-o[^\r\n]*CompilerId${lang}(/CompilerId${lang}.xctest)?/(\\./)?CompilerId${lang}[ \t\n\\\"]")
       set(_comp "${CMAKE_MATCH_2}")
       if(EXISTS "${_comp}")
         set(CMAKE_${lang}_COMPILER_ID_TOOL "${_comp}" PARENT_SCOPE)
@@ -335,7 +375,13 @@
     # binary dir.
     file(GLOB files
       RELATIVE ${CMAKE_${lang}_COMPILER_ID_DIR}
-      ${CMAKE_${lang}_COMPILER_ID_DIR}/*)
+
+      # normal case
+      ${CMAKE_${lang}_COMPILER_ID_DIR}/*
+
+      # com.apple.package-type.bundle.unit-test
+      ${CMAKE_${lang}_COMPILER_ID_DIR}/*.xctest/*
+      )
     list(REMOVE_ITEM files "${src}")
     set(COMPILER_${lang}_PRODUCED_FILES "")
     foreach(file ${files})
@@ -373,7 +419,7 @@
     set(SIMULATE_ID)
     set(SIMULATE_VERSION)
     file(STRINGS ${file}
-      CMAKE_${lang}_COMPILER_ID_STRINGS LIMIT_COUNT 6 REGEX "INFO:")
+      CMAKE_${lang}_COMPILER_ID_STRINGS LIMIT_COUNT 6 REGEX "INFO:[A-Za-z0-9_]+\\[[^]]*\\]")
     set(COMPILER_ID_TWICE)
     foreach(info ${CMAKE_${lang}_COMPILER_ID_STRINGS})
       if("${info}" MATCHES "INFO:compiler\\[([^]\"]*)\\]")
diff --git a/Modules/CMakeDetermineSystem.cmake b/Modules/CMakeDetermineSystem.cmake
index 1c0941a..fe292ea 100644
--- a/Modules/CMakeDetermineSystem.cmake
+++ b/Modules/CMakeDetermineSystem.cmake
@@ -47,7 +47,7 @@
   if(CMAKE_UNAME)
     exec_program(uname ARGS -s OUTPUT_VARIABLE CMAKE_HOST_SYSTEM_NAME)
     exec_program(uname ARGS -r OUTPUT_VARIABLE CMAKE_HOST_SYSTEM_VERSION)
-    if(CMAKE_HOST_SYSTEM_NAME MATCHES "Linux|CYGWIN.*|Darwin")
+    if(CMAKE_HOST_SYSTEM_NAME MATCHES "Linux|CYGWIN.*|Darwin|^GNU$")
       exec_program(uname ARGS -m OUTPUT_VARIABLE CMAKE_HOST_SYSTEM_PROCESSOR
         RETURN_VALUE val)
       if(CMAKE_HOST_SYSTEM_NAME STREQUAL "Darwin" AND
diff --git a/Modules/CMakeExpandImportedTargets.cmake b/Modules/CMakeExpandImportedTargets.cmake
index 0752e04..8ac3364 100644
--- a/Modules/CMakeExpandImportedTargets.cmake
+++ b/Modules/CMakeExpandImportedTargets.cmake
@@ -20,8 +20,9 @@
 #
 # ::
 #
-#     cmake_expand_imported_targets(expandedLibs LIBRARIES ${CMAKE_REQUIRED_LIBRARIES}
-#                                                CONFIGURATION "${CMAKE_TRY_COMPILE_CONFIGURATION}" )
+#     cmake_expand_imported_targets(expandedLibs
+#       LIBRARIES ${CMAKE_REQUIRED_LIBRARIES}
+#       CONFIGURATION "${CMAKE_TRY_COMPILE_CONFIGURATION}" )
 
 
 #=============================================================================
@@ -71,7 +72,11 @@
       set(_CCSR_NEW_REQ_LIBS )
       set(_CHECK_FOR_IMPORTED_TARGETS FALSE)
       foreach(_CURRENT_LIB ${_CCSR_REQ_LIBS})
-         get_target_property(_importedConfigs "${_CURRENT_LIB}" IMPORTED_CONFIGURATIONS)
+         if(TARGET "${_CURRENT_LIB}")
+           get_target_property(_importedConfigs "${_CURRENT_LIB}" IMPORTED_CONFIGURATIONS)
+         else()
+           set(_importedConfigs "")
+         endif()
          if (_importedConfigs)
 #            message(STATUS "Detected imported target ${_CURRENT_LIB}")
             # Ok, so this is an imported target.
@@ -123,7 +128,11 @@
    # all remaining imported target names (there shouldn't be any left anyway).
    set(_CCSR_NEW_REQ_LIBS )
    foreach(_CURRENT_LIB ${_CCSR_REQ_LIBS})
-      get_target_property(_importedConfigs "${_CURRENT_LIB}" IMPORTED_CONFIGURATIONS)
+      if(TARGET "${_CURRENT_LIB}")
+        get_target_property(_importedConfigs "${_CURRENT_LIB}" IMPORTED_CONFIGURATIONS)
+      else()
+        set(_importedConfigs "")
+      endif()
       if (NOT _importedConfigs)
          list(APPEND _CCSR_NEW_REQ_LIBS "${_CURRENT_LIB}" )
 #         message(STATUS "final: appending ${_CURRENT_LIB}")
diff --git a/Modules/CMakeFindBinUtils.cmake b/Modules/CMakeFindBinUtils.cmake
index 829b6ff..e0ba131 100644
--- a/Modules/CMakeFindBinUtils.cmake
+++ b/Modules/CMakeFindBinUtils.cmake
@@ -35,7 +35,8 @@
    OR "${CMAKE_Fortran_SIMULATE_ID}" STREQUAL "MSVC"
    OR "${CMAKE_C_COMPILER_ID}" STREQUAL "MSVC"
    OR "${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC"
-   OR "${CMAKE_GENERATOR}" MATCHES "Visual Studio")
+   OR ("${CMAKE_GENERATOR}" MATCHES "Visual Studio"
+       AND NOT CMAKE_VS_PLATFORM_NAME STREQUAL "Tegra-Android"))
 
   find_program(CMAKE_LINKER NAMES link HINTS ${_CMAKE_TOOLCHAIN_LOCATION})
 
@@ -66,9 +67,7 @@
 
 endif()
 
-
-# on Apple there really should be install_name_tool
-if(APPLE)
+if(CMAKE_PLATFORM_HAS_INSTALLNAME)
   find_program(CMAKE_INSTALL_NAME_TOOL NAMES install_name_tool HINTS ${_CMAKE_TOOLCHAIN_LOCATION})
 
   if(NOT CMAKE_INSTALL_NAME_TOOL)
diff --git a/Modules/CMakeFindPackageMode.cmake b/Modules/CMakeFindPackageMode.cmake
index 9f97ee5..fc3058d 100644
--- a/Modules/CMakeFindPackageMode.cmake
+++ b/Modules/CMakeFindPackageMode.cmake
@@ -7,15 +7,24 @@
 # This file is executed by cmake when invoked with --find-package.  It
 # expects that the following variables are set using -D:
 #
-# ::
-#
-#    NAME = name of the package
-#    COMPILER_ID = the CMake compiler ID for which the result is, i.e. GNU/Intel/Clang/MSVC, etc.
-#    LANGUAGE = language for which the result will be used, i.e. C/CXX/Fortan/ASM
-#    MODE = EXIST : only check for existence of the given package
-#           COMPILE : print the flags needed for compiling an object file which uses the given package
-#           LINK : print the flags needed for linking when using the given package
-#    QUIET = if TRUE, don't print anything
+# ``NAME``
+#   name of the package
+# ``COMPILER_ID``
+#   the CMake compiler ID for which the result is,
+#   i.e. GNU/Intel/Clang/MSVC, etc.
+# ``LANGUAGE``
+#   language for which the result will be used,
+#   i.e. C/CXX/Fortan/ASM
+# ``MODE``
+#   ``EXIST``
+#     only check for existence of the given package
+#   ``COMPILE``
+#     print the flags needed for compiling an object file which uses
+#     the given package
+#   ``LINK``
+#     print the flags needed for linking when using the given package
+# ``QUIET``
+#   if TRUE, don't print anything
 
 #=============================================================================
 # Copyright 2006-2011 Alexander Neundorf, <neundorf@kde.org>
diff --git a/Modules/CMakePackageConfigHelpers.cmake b/Modules/CMakePackageConfigHelpers.cmake
index 473bbe5..206ea7a 100644
--- a/Modules/CMakePackageConfigHelpers.cmake
+++ b/Modules/CMakePackageConfigHelpers.cmake
@@ -2,29 +2,37 @@
 # CMakePackageConfigHelpers
 # -------------------------
 #
-# CONFIGURE_PACKAGE_CONFIG_FILE(), WRITE_BASIC_PACKAGE_VERSION_FILE()
+# Helpers functions for creating config files that can be included by other
+# projects to find and use a package.
 #
+# Adds the :command:`configure_package_config_file()` and
+# :command:`write_basic_package_version_file()` commands.
 #
+# Generating a Package Configuration File
+# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 #
-# ::
+# .. command:: configure_package_config_file
 #
-#     CONFIGURE_PACKAGE_CONFIG_FILE(<input> <output> INSTALL_DESTINATION <path>
-#                                                    [PATH_VARS <var1> <var2> ... <varN>]
-#                                                    [NO_SET_AND_CHECK_MACRO]
-#                                                    [NO_CHECK_REQUIRED_COMPONENTS_MACRO])
+#  Create a config file for a project::
 #
+#    configure_package_config_file(<input> <output>
+#      INSTALL_DESTINATION <path>
+#      [PATH_VARS <var1> <var2> ... <varN>]
+#      [NO_SET_AND_CHECK_MACRO]
+#      [NO_CHECK_REQUIRED_COMPONENTS_MACRO]
+#      [INSTALL_PREFIX <path>]
+#      )
 #
+# ``configure_package_config_file()`` should be used instead of the plain
+# :command:`configure_file()` command when creating the ``<Name>Config.cmake``
+# or ``<Name>-config.cmake`` file for installing a project or library.  It helps
+# making the resulting package relocatable by avoiding hardcoded paths in the
+# installed ``Config.cmake`` file.
 #
-# CONFIGURE_PACKAGE_CONFIG_FILE() should be used instead of the plain
-# configure_file() command when creating the <Name>Config.cmake or
-# <Name>-config.cmake file for installing a project or library.  It
-# helps making the resulting package relocatable by avoiding hardcoded
-# paths in the installed Config.cmake file.
+# In a ``FooConfig.cmake`` file there may be code like this to make the install
+# destinations know to the using project:
 #
-# In a FooConfig.cmake file there may be code like this to make the
-# install destinations know to the using project:
-#
-# ::
+# .. code-block:: cmake
 #
 #    set(FOO_INCLUDE_DIR   "@CMAKE_INSTALL_FULL_INCLUDEDIR@" )
 #    set(FOO_DATA_DIR   "@CMAKE_INSTALL_PREFIX@/@RELATIVE_DATA_INSTALL_DIR@" )
@@ -32,141 +40,154 @@
 #    ...logic to determine installedPrefix from the own location...
 #    set(FOO_CONFIG_DIR  "${installedPrefix}/@CONFIG_INSTALL_DIR@" )
 #
-# All 4 options shown above are not sufficient, since the first 3
-# hardcode the absolute directory locations, and the 4th case works only
-# if the logic to determine the installedPrefix is correct, and if
-# CONFIG_INSTALL_DIR contains a relative path, which in general cannot
-# be guaranteed.  This has the effect that the resulting FooConfig.cmake
-# file would work poorly under Windows and OSX, where users are used to
-# choose the install location of a binary package at install time,
-# independent from how CMAKE_INSTALL_PREFIX was set at build/cmake time.
+# All 4 options shown above are not sufficient, since the first 3 hardcode the
+# absolute directory locations, and the 4th case works only if the logic to
+# determine the ``installedPrefix`` is correct, and if ``CONFIG_INSTALL_DIR``
+# contains a relative path, which in general cannot be guaranteed.  This has the
+# effect that the resulting ``FooConfig.cmake`` file would work poorly under
+# Windows and OSX, where users are used to choose the install location of a
+# binary package at install time, independent from how
+# :variable:`CMAKE_INSTALL_PREFIX` was set at build/cmake time.
 #
-# Using CONFIGURE_PACKAGE_CONFIG_FILE() helps.  If used correctly, it
-# makes the resulting FooConfig.cmake file relocatable.  Usage:
+# Using ``configure_package_config_file`` helps.  If used correctly, it makes
+# the resulting ``FooConfig.cmake`` file relocatable.  Usage:
 #
-# ::
-#
-#    1. write a FooConfig.cmake.in file as you are used to
-#    2. insert a line containing only the string "@PACKAGE_INIT@"
-#    3. instead of set(FOO_DIR "@SOME_INSTALL_DIR@"), use set(FOO_DIR "@PACKAGE_SOME_INSTALL_DIR@")
-#       (this must be after the @PACKAGE_INIT@ line)
-#    4. instead of using the normal configure_file(), use CONFIGURE_PACKAGE_CONFIG_FILE()
+# 1. write a ``FooConfig.cmake.in`` file as you are used to
+# 2. insert a line containing only the string ``@PACKAGE_INIT@``
+# 3. instead of ``set(FOO_DIR "@SOME_INSTALL_DIR@")``, use
+#    ``set(FOO_DIR "@PACKAGE_SOME_INSTALL_DIR@")`` (this must be after the
+#    ``@PACKAGE_INIT@`` line)
+# 4. instead of using the normal :command:`configure_file()`, use
+#    ``configure_package_config_file()``
 #
 #
 #
-# The <input> and <output> arguments are the input and output file, the
-# same way as in configure_file().
+# The ``<input>`` and ``<output>`` arguments are the input and output file, the
+# same way as in :command:`configure_file()`.
 #
-# The <path> given to INSTALL_DESTINATION must be the destination where
-# the FooConfig.cmake file will be installed to.  This can either be a
-# relative or absolute path, both work.
+# The ``<path>`` given to ``INSTALL_DESTINATION`` must be the destination where
+# the ``FooConfig.cmake`` file will be installed to.  This path can either be
+# absolute, or relative to the ``INSTALL_PREFIX`` path.
 #
-# The variables <var1> to <varN> given as PATH_VARS are the variables
-# which contain install destinations.  For each of them the macro will
-# create a helper variable PACKAGE_<var...>.  These helper variables
-# must be used in the FooConfig.cmake.in file for setting the installed
-# location.  They are calculated by CONFIGURE_PACKAGE_CONFIG_FILE() so
-# that they are always relative to the installed location of the
-# package.  This works both for relative and also for absolute
-# locations.  For absolute locations it works only if the absolute
-# location is a subdirectory of CMAKE_INSTALL_PREFIX.
+# The variables ``<var1>`` to ``<varN>`` given as ``PATH_VARS`` are the
+# variables which contain install destinations.  For each of them the macro will
+# create a helper variable ``PACKAGE_<var...>``.  These helper variables must be
+# used in the ``FooConfig.cmake.in`` file for setting the installed location.
+# They are calculated by ``configure_package_config_file`` so that they are
+# always relative to the installed location of the package.  This works both for
+# relative and also for absolute locations.  For absolute locations it works
+# only if the absolute location is a subdirectory of ``INSTALL_PREFIX``.
 #
-# By default configure_package_config_file() also generates two helper
-# macros, set_and_check() and check_required_components() into the
-# FooConfig.cmake file.
+# If the ``INSTALL_PREFIX`` argument is passed, this is used as base path to
+# calculate all the relative paths.  The ``<path>`` argument must be an absolute
+# path.  If this argument is not passed, the :variable:`CMAKE_INSTALL_PREFIX`
+# variable will be used instead.  The default value is good when generating a
+# FooConfig.cmake file to use your package from the install tree.  When
+# generating a FooConfig.cmake file to use your package from the build tree this
+# option should be used.
 #
-# set_and_check() should be used instead of the normal set() command for
-# setting directories and file locations.  Additionally to setting the
-# variable it also checks that the referenced file or directory actually
-# exists and fails with a FATAL_ERROR otherwise.  This makes sure that
-# the created FooConfig.cmake file does not contain wrong references.
-# When using the NO_SET_AND_CHECK_MACRO, this macro is not generated
-# into the FooConfig.cmake file.
+# By default ``configure_package_config_file`` also generates two helper macros,
+# ``set_and_check()`` and ``check_required_components()`` into the
+# ``FooConfig.cmake`` file.
 #
-# check_required_components(<package_name>) should be called at the end
-# of the FooConfig.cmake file if the package supports components.  This
-# macro checks whether all requested, non-optional components have been
-# found, and if this is not the case, sets the Foo_FOUND variable to
-# FALSE, so that the package is considered to be not found.  It does
-# that by testing the Foo_<Component>_FOUND variables for all requested
-# required components.  When using the NO_CHECK_REQUIRED_COMPONENTS
-# option, this macro is not generated into the FooConfig.cmake file.
+# ``set_and_check()`` should be used instead of the normal ``set()`` command for
+# setting directories and file locations.  Additionally to setting the variable
+# it also checks that the referenced file or directory actually exists and fails
+# with a ``FATAL_ERROR`` otherwise.  This makes sure that the created
+# ``FooConfig.cmake`` file does not contain wrong references.
+# When using the ``NO_SET_AND_CHECK_MACRO``, this macro is not generated
+# into the ``FooConfig.cmake`` file.
+#
+# ``check_required_components(<package_name>)`` should be called at the end of
+# the ``FooConfig.cmake`` file if the package supports components.  This macro
+# checks whether all requested, non-optional components have been found, and if
+# this is not the case, sets the ``Foo_FOUND`` variable to ``FALSE``, so that
+# the package is considered to be not found.  It does that by testing the
+# ``Foo_<Component>_FOUND`` variables for all requested required components.
+# When using the ``NO_CHECK_REQUIRED_COMPONENTS_MACRO`` option, this macro is
+# not generated into the ``FooConfig.cmake`` file.
 #
 # For an example see below the documentation for
-# WRITE_BASIC_PACKAGE_VERSION_FILE().
+# :command:`write_basic_package_version_file()`.
+#
+# Generating a Package Version File
+# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+#
+# .. command:: write_basic_package_version_file
+#
+#  Create a version file for a project::
+#
+#    write_basic_package_version_file(<filename>
+#      [VERSION <major.minor.patch>]
+#      COMPATIBILITY <AnyNewerVersion|SameMajorVersion|ExactVersion> )
 #
 #
+# Writes a file for use as ``<package>ConfigVersion.cmake`` file to
+# ``<filename>``.  See the documentation of :command:`find_package()` for
+# details on this.
 #
-# ::
+# ``<filename>`` is the output filename, it should be in the build tree.
+# ``<major.minor.patch>`` is the version number of the project to be installed.
 #
-#   WRITE_BASIC_PACKAGE_VERSION_FILE( filename [VERSION major.minor.patch] COMPATIBILITY (AnyNewerVersion|SameMajorVersion|ExactVersion) )
+# If no ``VERSION`` is given, the :variable:`PROJECT_VERSION` variable is used.
+# If this hasn't been set, it errors out.
 #
+# The ``COMPATIBILITY`` mode ``AnyNewerVersion`` means that the installed
+# package version will be considered compatible if it is newer or exactly the
+# same as the requested version.  This mode should be used for packages which
+# are fully backward compatible, also across major versions.
+# If ``SameMajorVersion`` is used instead, then the behaviour differs from
+# ``AnyNewerVersion`` in that the major version number must be the same as
+# requested, e.g.  version 2.0 will not be considered compatible if 1.0 is
+# requested.  This mode should be used for packages which guarantee backward
+# compatibility within the same major version.
+# If ``ExactVersion`` is used, then the package is only considered compatible if
+# the requested version matches exactly its own version number (not considering
+# the tweak version).  For example, version 1.2.3 of a package is only
+# considered compatible to requested version 1.2.3.  This mode is for packages
+# without compatibility guarantees.
+# If your project has more elaborated version matching rules, you will need to
+# write your own custom ``ConfigVersion.cmake`` file instead of using this
+# macro.
 #
-#
-# Writes a file for use as <package>ConfigVersion.cmake file to
-# <filename>.  See the documentation of find_package() for details on
-# this.
-#
-# ::
-#
-#     filename is the output filename, it should be in the build tree.
-#     major.minor.patch is the version number of the project to be installed
-#
-# If no ``VERSION`` is given, the :variable:`PROJECT_VERSION` variable
-# is used.  If this hasn't been set, it errors out.
-#
-# The COMPATIBILITY mode AnyNewerVersion means that the installed
-# package version will be considered compatible if it is newer or
-# exactly the same as the requested version.  This mode should be used
-# for packages which are fully backward compatible, also across major
-# versions.  If SameMajorVersion is used instead, then the behaviour
-# differs from AnyNewerVersion in that the major version number must be
-# the same as requested, e.g.  version 2.0 will not be considered
-# compatible if 1.0 is requested.  This mode should be used for packages
-# which guarantee backward compatibility within the same major version.
-# If ExactVersion is used, then the package is only considered
-# compatible if the requested version matches exactly its own version
-# number (not considering the tweak version).  For example, version
-# 1.2.3 of a package is only considered compatible to requested version
-# 1.2.3.  This mode is for packages without compatibility guarantees.
-# If your project has more elaborated version matching rules, you will
-# need to write your own custom ConfigVersion.cmake file instead of
-# using this macro.
-#
-# Internally, this macro executes configure_file() to create the
-# resulting version file.  Depending on the COMPATIBLITY, either the
-# file BasicConfigVersion-SameMajorVersion.cmake.in or
-# BasicConfigVersion-AnyNewerVersion.cmake.in is used.  Please note that
+# Internally, this macro executes :command:`configure_file()` to create the
+# resulting version file.  Depending on the ``COMPATIBLITY``, either the file
+# ``BasicConfigVersion-SameMajorVersion.cmake.in`` or
+# ``BasicConfigVersion-AnyNewerVersion.cmake.in`` is used.  Please note that
 # these two files are internal to CMake and you should not call
-# configure_file() on them yourself, but they can be used as starting
-# point to create more sophisticted custom ConfigVersion.cmake files.
+# :command:`configure_file()` on them yourself, but they can be used as starting
+# point to create more sophisticted custom ``ConfigVersion.cmake`` files.
 #
+# Example Generating Package Files
+# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 #
+# Example using both :command:`configure_package_config_file` and
+# ``write_basic_package_version_file()``:
 #
-# Example using both configure_package_config_file() and
-# write_basic_package_version_file(): CMakeLists.txt:
+# ``CMakeLists.txt``:
 #
-# ::
+# .. code-block:: cmake
 #
 #    set(INCLUDE_INSTALL_DIR include/ ... CACHE )
 #    set(LIB_INSTALL_DIR lib/ ... CACHE )
 #    set(SYSCONFIG_INSTALL_DIR etc/foo/ ... CACHE )
 #    ...
 #    include(CMakePackageConfigHelpers)
-#    configure_package_config_file(FooConfig.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/FooConfig.cmake
-#                                  INSTALL_DESTINATION ${LIB_INSTALL_DIR}/Foo/cmake
-#                                  PATH_VARS INCLUDE_INSTALL_DIR SYSCONFIG_INSTALL_DIR)
-#    write_basic_package_version_file(${CMAKE_CURRENT_BINARY_DIR}/FooConfigVersion.cmake
-#                                     VERSION 1.2.3
-#                                     COMPATIBILITY SameMajorVersion )
-#    install(FILES ${CMAKE_CURRENT_BINARY_DIR}/FooConfig.cmake ${CMAKE_CURRENT_BINARY_DIR}/FooConfigVersion.cmake
+#    configure_package_config_file(FooConfig.cmake.in
+#      ${CMAKE_CURRENT_BINARY_DIR}/FooConfig.cmake
+#      INSTALL_DESTINATION ${LIB_INSTALL_DIR}/Foo/cmake
+#      PATH_VARS INCLUDE_INSTALL_DIR SYSCONFIG_INSTALL_DIR)
+#    write_basic_package_version_file(
+#      ${CMAKE_CURRENT_BINARY_DIR}/FooConfigVersion.cmake
+#      VERSION 1.2.3
+#      COMPATIBILITY SameMajorVersion )
+#    install(FILES ${CMAKE_CURRENT_BINARY_DIR}/FooConfig.cmake
+#                  ${CMAKE_CURRENT_BINARY_DIR}/FooConfigVersion.cmake
 #            DESTINATION ${LIB_INSTALL_DIR}/Foo/cmake )
 #
+# ``FooConfig.cmake.in``:
 #
-#
-# With a FooConfig.cmake.in:
-#
-# ::
+# .. code-block:: cmake
 #
 #    set(FOO_VERSION x.y.z)
 #    ...
@@ -175,10 +196,6 @@
 #    set_and_check(FOO_INCLUDE_DIR "@PACKAGE_INCLUDE_INSTALL_DIR@")
 #    set_and_check(FOO_SYSCONFIG_DIR "@PACKAGE_SYSCONFIG_INSTALL_DIR@")
 #
-#
-#
-# ::
-#
 #    check_required_components(Foo)
 
 
@@ -203,11 +220,9 @@
   write_basic_config_version_file(${ARGN})
 endmacro()
 
-set(cfpch_dir ${CMAKE_CURRENT_LIST_DIR})
-
 function(CONFIGURE_PACKAGE_CONFIG_FILE _inputFile _outputFile)
   set(options NO_SET_AND_CHECK_MACRO NO_CHECK_REQUIRED_COMPONENTS_MACRO)
-  set(oneValueArgs INSTALL_DESTINATION )
+  set(oneValueArgs INSTALL_DESTINATION INSTALL_PREFIX)
   set(multiValueArgs PATH_VARS )
 
   cmake_parse_arguments(CCF "${options}" "${oneValueArgs}" "${multiValueArgs}"  ${ARGN})
@@ -220,20 +235,30 @@
     message(FATAL_ERROR "No INSTALL_DESTINATION given to CONFIGURE_PACKAGE_CONFIG_FILE()")
   endif()
 
+  if(DEFINED CCF_INSTALL_PREFIX)
+    if(IS_ABSOLUTE "${CCF_INSTALL_PREFIX}")
+      set(installPrefix "${CCF_INSTALL_PREFIX}")
+    else()
+      message(FATAL_ERROR "INSTALL_PREFIX must be an absolute path")
+    endif()
+  else()
+    set(installPrefix "${CMAKE_INSTALL_PREFIX}")
+  endif()
+
   if(IS_ABSOLUTE "${CCF_INSTALL_DESTINATION}")
     set(absInstallDir "${CCF_INSTALL_DESTINATION}")
   else()
-    set(absInstallDir "${CMAKE_INSTALL_PREFIX}/${CCF_INSTALL_DESTINATION}")
+    set(absInstallDir "${installPrefix}/${CCF_INSTALL_DESTINATION}")
   endif()
 
-  file(RELATIVE_PATH PACKAGE_RELATIVE_PATH "${absInstallDir}" "${CMAKE_INSTALL_PREFIX}" )
+  file(RELATIVE_PATH PACKAGE_RELATIVE_PATH "${absInstallDir}" "${installPrefix}" )
 
   foreach(var ${CCF_PATH_VARS})
     if(NOT DEFINED ${var})
       message(FATAL_ERROR "Variable ${var} does not exist")
     else()
       if(IS_ABSOLUTE "${${var}}")
-        string(REPLACE "${CMAKE_INSTALL_PREFIX}" "\${PACKAGE_PREFIX_DIR}"
+        string(REPLACE "${installPrefix}" "\${PACKAGE_PREFIX_DIR}"
                         PACKAGE_${var} "${${var}}")
       else()
         set(PACKAGE_${var} "\${PACKAGE_PREFIX_DIR}/${${var}}")
@@ -259,7 +284,7 @@
 get_filename_component(_realCurr \"\${CMAKE_CURRENT_LIST_DIR}\" REALPATH)
 get_filename_component(_realOrig \"${absInstallDir}\" REALPATH)
 if(_realCurr STREQUAL _realOrig)
-  set(PACKAGE_PREFIX_DIR \"${CMAKE_INSTALL_PREFIX}\")
+  set(PACKAGE_PREFIX_DIR \"${installPrefix}\")
 endif()
 unset(_realOrig)
 unset(_realCurr)
diff --git a/Modules/CMakeParseArguments.cmake b/Modules/CMakeParseArguments.cmake
index 4248176..8553f38 100644
--- a/Modules/CMakeParseArguments.cmake
+++ b/Modules/CMakeParseArguments.cmake
@@ -45,7 +45,8 @@
 #      set(options OPTIONAL FAST)
 #      set(oneValueArgs DESTINATION RENAME)
 #      set(multiValueArgs TARGETS CONFIGURATIONS)
-#      cmake_parse_arguments(MY_INSTALL "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN} )
+#      cmake_parse_arguments(MY_INSTALL "${options}" "${oneValueArgs}"
+#                            "${multiValueArgs}" ${ARGN} )
 #      ...
 #
 #
diff --git a/Modules/CMakePrintHelpers.cmake b/Modules/CMakePrintHelpers.cmake
index ad3b0d5..474fa41 100644
--- a/Modules/CMakePrintHelpers.cmake
+++ b/Modules/CMakePrintHelpers.cmake
@@ -15,11 +15,10 @@
 #
 # This macro prints the values of the properties of the given targets,
 # source files, directories, tests or cache entries.  Exactly one of the
-# scope keywords must be used.  Example:
+# scope keywords must be used.  Example::
 #
-# ::
-#
-#    cmake_print_properties(TARGETS foo bar PROPERTIES LOCATION INTERFACE_INCLUDE_DIRS)
+#    cmake_print_properties(TARGETS foo bar PROPERTIES
+#                           LOCATION INTERFACE_INCLUDE_DIRS)
 #
 # This will print the LOCATION and INTERFACE_INCLUDE_DIRS properties for
 # both targets foo and bar.
@@ -29,17 +28,13 @@
 # CMAKE_PRINT_VARIABLES(var1 var2 ..  varN)
 #
 # This macro will print the name of each variable followed by its value.
-# Example:
+# Example::
 #
-# ::
+#   cmake_print_variables(CMAKE_C_COMPILER CMAKE_MAJOR_VERSION DOES_NOT_EXIST)
 #
-#    cmake_print_variables(CMAKE_C_COMPILER CMAKE_MAJOR_VERSION THIS_ONE_DOES_NOT_EXIST)
+# Gives::
 #
-# Gives:
-#
-# ::
-#
-#    -- CMAKE_C_COMPILER="/usr/bin/gcc" ; CMAKE_MAJOR_VERSION="2" ; THIS_ONE_DOES_NOT_EXIST=""
+#   -- CMAKE_C_COMPILER="/usr/bin/gcc" ; CMAKE_MAJOR_VERSION="2" ; DOES_NOT_EXIST=""
 
 #=============================================================================
 # Copyright 2013 Alexander Neundorf, <neundorf@kde.org>
diff --git a/Modules/CPack.cmake b/Modules/CPack.cmake
index 89547af..35259c4 100644
--- a/Modules/CPack.cmake
+++ b/Modules/CPack.cmake
@@ -418,35 +418,41 @@
       if(APPLE)
         option(CPACK_BINARY_BUNDLE       "Enable to build OSX bundles"      OFF)
         option(CPACK_BINARY_DRAGNDROP    "Enable to build OSX Drag And Drop package" OFF)
-        option(CPACK_BINARY_PACKAGEMAKER "Enable to build PackageMaker packages" OFF)
         option(CPACK_BINARY_OSXX11       "Enable to build OSX X11 packages"      OFF)
+        option(CPACK_BINARY_PACKAGEMAKER "Enable to build PackageMaker packages" OFF)
       else()
         option(CPACK_BINARY_TZ  "Enable to build TZ packages"     ON)
       endif()
-      option(CPACK_BINARY_STGZ "Enable to build STGZ packages"    ON)
-      option(CPACK_BINARY_TGZ  "Enable to build TGZ packages"     ON)
-      option(CPACK_BINARY_TBZ2 "Enable to build TBZ2 packages"    OFF)
       option(CPACK_BINARY_DEB  "Enable to build Debian packages"  OFF)
-      option(CPACK_BINARY_RPM  "Enable to build RPM packages"     OFF)
       option(CPACK_BINARY_NSIS "Enable to build NSIS packages"    OFF)
+      option(CPACK_BINARY_RPM  "Enable to build RPM packages"     OFF)
+      option(CPACK_BINARY_STGZ "Enable to build STGZ packages"    ON)
+      option(CPACK_BINARY_TBZ2 "Enable to build TBZ2 packages"    OFF)
+      option(CPACK_BINARY_TGZ  "Enable to build TGZ packages"     ON)
+      option(CPACK_BINARY_TXZ  "Enable to build TXZ packages"     OFF)
     endif()
   else()
+    option(CPACK_BINARY_7Z   "Enable to build 7-Zip packages" OFF)
     option(CPACK_BINARY_NSIS "Enable to build NSIS packages" ON)
     option(CPACK_BINARY_WIX  "Enable to build WiX packages" OFF)
     option(CPACK_BINARY_ZIP  "Enable to build ZIP packages" OFF)
   endif()
+  option(CPACK_BINARY_IFW "Enable to build IFW packages" OFF)
 
+  cpack_optional_append(CPACK_GENERATOR  CPACK_BINARY_7Z           7Z)
   cpack_optional_append(CPACK_GENERATOR  CPACK_BINARY_BUNDLE       Bundle)
-  cpack_optional_append(CPACK_GENERATOR  CPACK_BINARY_DRAGNDROP    DragNDrop)
-  cpack_optional_append(CPACK_GENERATOR  CPACK_BINARY_PACKAGEMAKER PackageMaker)
-  cpack_optional_append(CPACK_GENERATOR  CPACK_BINARY_OSXX11       OSXX11)
   cpack_optional_append(CPACK_GENERATOR  CPACK_BINARY_CYGWIN       CygwinBinary)
   cpack_optional_append(CPACK_GENERATOR  CPACK_BINARY_DEB          DEB)
-  cpack_optional_append(CPACK_GENERATOR  CPACK_BINARY_RPM          RPM)
+  cpack_optional_append(CPACK_GENERATOR  CPACK_BINARY_DRAGNDROP    DragNDrop)
+  cpack_optional_append(CPACK_GENERATOR  CPACK_BINARY_IFW          IFW)
   cpack_optional_append(CPACK_GENERATOR  CPACK_BINARY_NSIS         NSIS)
+  cpack_optional_append(CPACK_GENERATOR  CPACK_BINARY_OSXX11       OSXX11)
+  cpack_optional_append(CPACK_GENERATOR  CPACK_BINARY_PACKAGEMAKER PackageMaker)
+  cpack_optional_append(CPACK_GENERATOR  CPACK_BINARY_RPM          RPM)
   cpack_optional_append(CPACK_GENERATOR  CPACK_BINARY_STGZ         STGZ)
-  cpack_optional_append(CPACK_GENERATOR  CPACK_BINARY_TGZ          TGZ)
   cpack_optional_append(CPACK_GENERATOR  CPACK_BINARY_TBZ2         TBZ2)
+  cpack_optional_append(CPACK_GENERATOR  CPACK_BINARY_TGZ          TGZ)
+  cpack_optional_append(CPACK_GENERATOR  CPACK_BINARY_TXZ          TXZ)
   cpack_optional_append(CPACK_GENERATOR  CPACK_BINARY_TZ           TZ)
   cpack_optional_append(CPACK_GENERATOR  CPACK_BINARY_WIX          WIX)
   cpack_optional_append(CPACK_GENERATOR  CPACK_BINARY_ZIP          ZIP)
@@ -461,27 +467,51 @@
     else()
       option(CPACK_SOURCE_TBZ2 "Enable to build TBZ2 source packages" ON)
       option(CPACK_SOURCE_TGZ  "Enable to build TGZ source packages"  ON)
+      option(CPACK_SOURCE_TXZ  "Enable to build TXZ source packages"  ON)
       option(CPACK_SOURCE_TZ   "Enable to build TZ source packages"   ON)
       option(CPACK_SOURCE_ZIP  "Enable to build ZIP source packages"  OFF)
     endif()
   else()
+    option(CPACK_SOURCE_7Z  "Enable to build 7-Zip source packages" ON)
     option(CPACK_SOURCE_ZIP "Enable to build ZIP source packages" ON)
   endif()
 
+  cpack_optional_append(CPACK_SOURCE_GENERATOR  CPACK_SOURCE_7Z      7Z)
   cpack_optional_append(CPACK_SOURCE_GENERATOR  CPACK_SOURCE_CYGWIN  CygwinSource)
-  cpack_optional_append(CPACK_SOURCE_GENERATOR  CPACK_SOURCE_TGZ     TGZ)
   cpack_optional_append(CPACK_SOURCE_GENERATOR  CPACK_SOURCE_TBZ2    TBZ2)
+  cpack_optional_append(CPACK_SOURCE_GENERATOR  CPACK_SOURCE_TGZ     TGZ)
+  cpack_optional_append(CPACK_SOURCE_GENERATOR  CPACK_SOURCE_TXZ     TXZ)
   cpack_optional_append(CPACK_SOURCE_GENERATOR  CPACK_SOURCE_TZ      TZ)
   cpack_optional_append(CPACK_SOURCE_GENERATOR  CPACK_SOURCE_ZIP     ZIP)
 endif()
 
 # mark the above options as advanced
-mark_as_advanced(CPACK_BINARY_CYGWIN CPACK_BINARY_PACKAGEMAKER CPACK_BINARY_OSXX11
-                 CPACK_BINARY_STGZ   CPACK_BINARY_TGZ          CPACK_BINARY_TBZ2
-                 CPACK_BINARY_DEB    CPACK_BINARY_RPM          CPACK_BINARY_TZ
-                 CPACK_BINARY_NSIS CPACK_BINARY_WIX CPACK_BINARY_ZIP CPACK_BINARY_BUNDLE
-                 CPACK_SOURCE_CYGWIN CPACK_SOURCE_TBZ2 CPACK_SOURCE_TGZ
-                 CPACK_SOURCE_TZ CPACK_SOURCE_ZIP CPACK_BINARY_DRAGNDROP)
+mark_as_advanced(
+  CPACK_BINARY_7Z
+  CPACK_BINARY_BUNDLE
+  CPACK_BINARY_CYGWIN
+  CPACK_BINARY_DEB
+  CPACK_BINARY_DRAGNDROP
+  CPACK_BINARY_IFW
+  CPACK_BINARY_NSIS
+  CPACK_BINARY_OSXX11
+  CPACK_BINARY_PACKAGEMAKER
+  CPACK_BINARY_RPM
+  CPACK_BINARY_STGZ
+  CPACK_BINARY_TBZ2
+  CPACK_BINARY_TGZ
+  CPACK_BINARY_TXZ
+  CPACK_BINARY_TZ
+  CPACK_BINARY_WIX
+  CPACK_BINARY_ZIP
+  CPACK_SOURCE_7Z
+  CPACK_SOURCE_CYGWIN
+  CPACK_SOURCE_TBZ2
+  CPACK_SOURCE_TGZ
+  CPACK_SOURCE_TXZ
+  CPACK_SOURCE_TZ
+  CPACK_SOURCE_ZIP
+  )
 
 # Set some other variables
 cpack_set_if_not_set(CPACK_INSTALL_CMAKE_PROJECTS
diff --git a/Modules/CPackComponent.cmake b/Modules/CPackComponent.cmake
index 1433d9e..5524a3f 100644
--- a/Modules/CPackComponent.cmake
+++ b/Modules/CPackComponent.cmake
@@ -458,6 +458,9 @@
   cpack_append_string_variable_set_command(
     CPACK_COMPONENT_GROUP_${CPACK_ADDGRP_UNAME}_DESCRIPTION
     CPACK_ADDGRP_STR)
+  cpack_append_string_variable_set_command(
+    CPACK_COMPONENT_GROUP_${CPACK_ADDGRP_UNAME}_PARENT_GROUP
+    CPACK_ADDGRP_STR)
   cpack_append_option_set_command(
     CPACK_COMPONENT_GROUP_${CPACK_ADDGRP_UNAME}_EXPANDED
     CPACK_ADDGRP_STR)
diff --git a/Modules/CPackIFW.cmake b/Modules/CPackIFW.cmake
new file mode 100644
index 0000000..4b8dc1e
--- /dev/null
+++ b/Modules/CPackIFW.cmake
@@ -0,0 +1,517 @@
+#.rst:
+# CPackIFW
+# --------
+#
+# .. _QtIFW: http://qt-project.org/doc/qtinstallerframework/index.html
+#
+# This module looks for the location of the command line utilities supplied with
+# the Qt Installer Framework (QtIFW_).
+#
+# The module also defines several commands to control the behavior of the
+# CPack ``IFW`` generator.
+#
+#
+# Overview
+# ^^^^^^^^
+#
+# CPack ``IFW`` generator helps you create online and offline
+# binary cross-platform installers with a graphical user interface.
+#
+# CPack IFW generator prepare project installation and generate configuration
+# and meta information for QtIFW_ tools.
+#
+# The QtIFW_ provides a set of tools and utilities to create
+# installers for the supported desktop Qt platforms: Linux, Microsoft Windows,
+# and Mac OS X.
+#
+# To use CPack ``IFW`` generator you must also install QtIFW_.
+# If you are not using the default path for the installation, please set
+# the path to the variable ``QTIFWDIR``.
+#
+# Variables
+# ^^^^^^^^^
+#
+# You can use the following variables to change behavior of CPack ``IFW`` generator.
+#
+# Package
+# """""""
+#
+# .. variable:: CPACK_IFW_PACKAGE_TITLE
+#
+#  Name of the installer as displayed on the title bar.
+#  By default used :variable:`CPACK_PACKAGE_DESCRIPTION_SUMMARY`
+#
+# .. variable:: CPACK_IFW_PACKAGE_PUBLISHER
+#
+#  Publisher of the software (as shown in the Windows Control Panel).
+#  By default used :variable:`CPACK_PACKAGE_VENDOR`
+#
+# .. variable:: CPACK_IFW_PRODUCT_URL
+#
+#  URL to a page that contains product information on your web site.
+#
+# .. variable:: CPACK_IFW_PACKAGE_ICON
+#
+#  Filename for a custom installer icon. The actual file is '.icns' (Mac OS X),
+#  '.ico' (Windows). No functionality on Unix.
+#
+# .. variable:: CPACK_IFW_PACKAGE_WINDOW_ICON
+#
+#  Filename for a custom window icon in PNG format for the Installer application.
+#
+# .. variable:: CPACK_IFW_PACKAGE_LOGO
+#
+#  Filename for a logo used as QWizard::LogoPixmap.
+#
+# .. variable:: CPACK_IFW_TARGET_DIRECTORY
+#
+#  Default target directory for installation.
+#  By default used "@ApplicationsDir@/:variable:`CPACK_PACKAGE_INSTALL_DIRECTORY`"
+#
+#  You can use predefined variables.
+#
+# .. variable:: CPACK_IFW_ADMIN_TARGET_DIRECTORY
+#
+#  Default target directory for installation with administrator rights.
+#
+#  You can use predefined variables.
+#
+# .. variable:: CPACK_IFW_PACKAGE_GROUP
+#
+#  The group, which will be used to configure the root package
+#
+# .. variable:: CPACK_IFW_PACKAGE_NAME
+#
+#  The root package name, which will be used if configuration group is not
+#  specified
+#
+# .. variable:: CPACK_IFW_REPOSITORIES_ALL
+#
+#  The list of remote repositories.
+#
+#  The default value of this variable is computed by CPack and contains
+#  all repositories added with command :command:`cpack_ifw_add_repository`
+#
+# .. variable:: CPACK_IFW_DOWNLOAD_ALL
+#
+#  If this is ``ON`` all components will be downloaded.
+#  By default is ``OFF`` or used value
+#  from :variable:`CPACK_DOWNLOAD_ALL` if set
+#
+# Components
+# """"""""""
+#
+# .. variable:: CPACK_IFW_RESOLVE_DUPLICATE_NAMES
+#
+#  Resolve duplicate names when installing components with groups.
+#
+# .. variable:: CPACK_IFW_PACKAGES_DIRECTORIES
+#
+#  Additional prepared packages dirs that will be used to resolve
+#  dependent components.
+#
+# Tools
+# """"""""
+#
+# .. variable:: CPACK_IFW_BINARYCREATOR_EXECUTABLE
+#
+#  The path to "binarycreator" command line client.
+#
+#  This variable is cached and can be configured user if need.
+#
+# .. variable:: CPACK_IFW_REPOGEN_EXECUTABLE
+#
+#  The path to "repogen" command line client.
+#
+#  This variable is cached and can be configured user if need.
+#
+# Commands
+# ^^^^^^^^^
+#
+# The module defines the following commands:
+#
+# --------------------------------------------------------------------------
+#
+# .. command:: cpack_ifw_configure_component
+#
+# Sets the arguments specific to the CPack IFW generator.
+#
+# ::
+#
+#   cpack_ifw_configure_component(<compname> [COMMON]
+#                       [NAME <name>]
+#                       [VERSION <version>]
+#                       [SCRIPT <script>]
+#                       [PRIORITY <priority>]
+#                       [DEPENDS <com_id> ...]
+#                       [LICENSES <display_name> <file_path> ...])
+#
+# This command should be called after cpack_add_component command.
+#
+# ``COMMON`` if set, then the component will be packaged and installed as part
+# of a group to which he belongs.
+#
+# ``VERSION`` is version of component.
+# By default used :variable:`CPACK_PACKAGE_VERSION`.
+#
+# ``SCRIPT`` is relative or absolute path to operations script
+# for this component.
+#
+# ``NAME`` is used to create domain-like identification for this component.
+# By default used origin component name.
+#
+# ``PRIORITY`` is priority of the component in the tree.
+#
+# ``DEPENDS`` list of dependency component identifiers in QtIFW_ style.
+#
+# ``LICENSES`` pair of <display_name> and <file_path> of license text for this
+# component. You can specify more then one license.
+#
+# --------------------------------------------------------------------------
+#
+# .. command:: cpack_ifw_configure_component_group
+#
+# Sets the arguments specific to the CPack IFW generator.
+#
+# ::
+#
+#   cpack_ifw_configure_component_group(<grpname>
+#                       [VERSION <version>]
+#                       [NAME <name>]
+#                       [SCRIPT <script>]
+#                       [PRIORITY <priority>]
+#                       [LICENSES <display_name> <file_path> ...])
+#
+# This command should be called after cpack_add_component_group command.
+#
+# ``VERSION`` is version of component group.
+# By default used :variable:`CPACK_PACKAGE_VERSION`.
+#
+# ``NAME`` is used to create domain-like identification for this component group.
+# By default used origin component group name.
+#
+# ``SCRIPT`` is relative or absolute path to operations script
+# for this component group.
+#
+# ``PRIORITY`` is priority of the component group in the tree.
+#
+# ``LICENSES`` pair of <display_name> and <file_path> of license text for this
+# component group. You can specify more then one license.
+#
+# --------------------------------------------------------------------------
+#
+# .. command:: cpack_ifw_add_repository
+#
+# Add QtIFW_ specific remote repository.
+#
+# ::
+#
+#   cpack_ifw_add_repository(<reponame> [DISABLED]
+#                       URL <url>
+#                       [USERNAME <username>]
+#                       [PASSWORD <password>]
+#                       [DISPLAY_NAME <display_name>])
+#
+# This macro will also add the <reponame> repository
+# to a variable :variable:`CPACK_IFW_REPOSITORIES_ALL`
+#
+# ``DISABLED`` if set, then the repository will be disabled by default.
+#
+# ``URL`` is points to a list of available components.
+#
+# ``USERNAME`` is used as user on a protected repository.
+#
+# ``PASSWORD`` is password to use on a protected repository.
+#
+# ``DISPLAY_NAME`` is string to display instead of the URL.
+#
+# Example usage
+# ^^^^^^^^^^^^^
+#
+# .. code-block:: cmake
+#
+#    set(CPACK_PACKAGE_NAME "MyPackage")
+#    set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "MyPackage Installation Example")
+#    set(CPACK_PACKAGE_VERSION "1.0.0") # Version of installer
+#
+#    include(CPack)
+#    include(CPackIFW)
+#
+#    cpack_add_component(myapp
+#        DISPLAY_NAME "MyApp"
+#        DESCRIPTION "My Application")
+#    cpack_ifw_configure_component(myapp
+#        VERSION "1.2.3" # Version of component
+#        SCRIPT "operations.qs")
+#    cpack_add_component(mybigplugin
+#        DISPLAY_NAME "MyBigPlugin"
+#        DESCRIPTION "My Big Downloadable Plugin"
+#        DOWNLOADED)
+#    cpack_ifw_add_repository(myrepo
+#        URL "http://example.com/ifw/repo/myapp"
+#        DISPLAY_NAME "My Application Repository")
+#
+#
+# Online installer
+# ^^^^^^^^^^^^^^^^
+#
+# By defaul CPack IFW generator make offline installer. This means that all
+# components will be packaged into a binary file.
+#
+# To make a component downloaded, you must set the ``DOWNLOADED`` option in
+# :command:`cpack_add_component`.
+#
+# Then you would use the command :command:`cpack_configure_downloads`.
+# If you set ``ALL`` option all components will be downloaded.
+#
+# You also can use command :command:`cpack_ifw_add_repository` and
+# variable :variable:`CPACK_IFW_DOWNLOAD_ALL` for more specific configuration.
+#
+# CPack IFW generator create "repository" dir in current binary dir. You
+# would copy content of this dir to specified ``site`` (``url``).
+#
+# See Also
+# ^^^^^^^^
+#
+# Qt Installer Framework Manual:
+#
+#  Index page
+#   http://qt-project.org/doc/qtinstallerframework/index.html
+#
+#  Component Scripting
+#   http://qt-project.org/doc/qtinstallerframework/scripting.html
+#
+#  Predefined Variables
+#   http://qt-project.org/doc/qtinstallerframework/scripting.html#predefined-variables
+#
+# Download Qt Installer Framework for you platform from Qt Project site:
+#  http://download.qt-project.org/official_releases/qt-installer-framework/
+#
+
+#=============================================================================
+# Copyright 2014 Kitware, Inc.
+# Copyright 2014 Konstantin Podsvirov <konstantin@podsvirov.pro>
+#
+# Distributed under the OSI-approved BSD License (the "License");
+# see accompanying file Copyright.txt for details.
+#
+# This software is distributed WITHOUT ANY WARRANTY; without even the
+# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+# See the License for more information.
+#=============================================================================
+# (To distribute this file outside of CMake, substitute the full
+#  License text for the above reference.)
+
+#=============================================================================
+# Search Qt Installer Framework tools
+#=============================================================================
+
+# Default path
+
+set(_CPACK_IFW_PATHS
+  "${QTIFWDIR}"
+  "$ENV{QTIFWDIR}"
+  "${QTDIR}"
+  "$ENV{QTIFWDIR}")
+if(WIN32)
+  list(APPEND _CPACK_IFW_PATHS
+    "$ENV{HOMEDRIVE}/Qt"
+    "C:/Qt")
+else()
+  list(APPEND _CPACK_IFW_PATHS
+    "$ENV{HOME}/Qt"
+    "/opt/Qt")
+endif()
+
+set(_CPACK_IFW_SUFFIXES
+  "bin"
+  "QtIFW-1.7.0/bin"
+  "QtIFW-1.6.0/bin"
+  "QtIFW-1.5.0/bin"
+  "QtIFW-1.4.0/bin"
+  "QtIFW-1.3.0/bin")
+
+# Look for 'binarycreator'
+
+find_program(CPACK_IFW_BINARYCREATOR_EXECUTABLE
+  NAMES binarycreator
+  PATHS ${_CPACK_IFW_PATHS}
+  PATH_SUFFIXES ${_CPACK_IFW_SUFFIXES}
+  DOC "QtIFW binarycreator command line client")
+
+mark_as_advanced(CPACK_IFW_BINARYCREATOR_EXECUTABLE)
+
+# Look for 'repogen'
+
+find_program(CPACK_IFW_REPOGEN_EXECUTABLE
+  NAMES repogen
+  PATHS ${_CPACK_IFW_PATHS}
+  PATH_SUFFIXES ${_CPACK_IFW_SUFFIXES}
+  DOC "QtIFW repogen command line client"
+  )
+mark_as_advanced(CPACK_IFW_REPOGEN_EXECUTABLE)
+
+#
+## Next code is included only once
+#
+
+if(NOT CPackIFW_CMake_INCLUDED)
+set(CPackIFW_CMake_INCLUDED 1)
+
+#=============================================================================
+# Macro definition
+#=============================================================================
+
+# Macro definition based on CPackComponent
+
+if(NOT CPackComponent_CMake_INCLUDED)
+    include(CPackComponent)
+endif()
+
+if(NOT __CMAKE_PARSE_ARGUMENTS_INCLUDED)
+    include(CMakeParseArguments)
+endif()
+
+# Resolve full filename for script file
+macro(_cpack_ifw_resolve_script _variable)
+  set(_ifw_script_macro ${_variable})
+  set(_ifw_script_file ${${_ifw_script_macro}})
+  if(DEFINED ${_ifw_script_macro})
+    get_filename_component(${_ifw_script_macro} ${_ifw_script_file} ABSOLUTE)
+    set(_ifw_script_file ${${_ifw_script_macro}})
+    if(NOT EXISTS ${_ifw_script_file})
+      message(WARNING "CPack IFW: script file \"${_ifw_script_file}\" is not exists")
+      set(${_ifw_script_macro})
+    endif()
+  endif()
+endmacro()
+
+# Resolve full path to lisense file
+macro(_cpack_ifw_resolve_lisenses _variable)
+  if(${_variable})
+    set(_ifw_license_file FALSE)
+    set(_ifw_licenses_fix)
+    foreach(_ifw_licenses_arg ${${_variable}})
+      if(_ifw_license_file)
+        get_filename_component(_ifw_licenses_arg "${_ifw_licenses_arg}" ABSOLUTE)
+        set(_ifw_license_file FALSE)
+      else()
+        set(_ifw_license_file TRUE)
+      endif()
+      list(APPEND _ifw_licenses_fix "${_ifw_licenses_arg}")
+    endforeach(_ifw_licenses_arg)
+    set(${_variable} "${_ifw_licenses_fix}")
+  endif()
+endmacro()
+
+# Macro for configure component
+macro(cpack_ifw_configure_component compname)
+
+  string(TOUPPER ${compname} _CPACK_IFWCOMP_UNAME)
+
+  set(_IFW_OPT COMMON)
+  set(_IFW_ARGS VERSION SCRIPT NAME PRIORITY)
+  set(_IFW_MULTI_ARGS DEPENDS LICENSES)
+  cmake_parse_arguments(CPACK_IFW_COMPONENT_${_CPACK_IFWCOMP_UNAME} "${_IFW_OPT}" "${_IFW_ARGS}" "${_IFW_MULTI_ARGS}" ${ARGN})
+
+  _cpack_ifw_resolve_script(CPACK_IFW_COMPONENT_${_CPACK_IFWCOMP_UNAME}_SCRIPT)
+  _cpack_ifw_resolve_lisenses(CPACK_IFW_COMPONENT_${_CPACK_IFWCOMP_UNAME}_LICENSES)
+
+  set(_CPACK_IFWCOMP_STR "\n# Configuration for IFW component \"${compname}\"\n")
+
+  foreach(_IFW_ARG_NAME ${_IFW_OPT})
+  cpack_append_option_set_command(
+    CPACK_IFW_COMPONENT_${_CPACK_IFWCOMP_UNAME}_${_IFW_ARG_NAME}
+    _CPACK_IFWCOMP_STR)
+  endforeach()
+
+  foreach(_IFW_ARG_NAME ${_IFW_ARGS})
+  cpack_append_string_variable_set_command(
+    CPACK_IFW_COMPONENT_${_CPACK_IFWCOMP_UNAME}_${_IFW_ARG_NAME}
+    _CPACK_IFWCOMP_STR)
+  endforeach()
+
+  foreach(_IFW_ARG_NAME ${_IFW_MULTI_ARGS})
+  cpack_append_variable_set_command(
+    CPACK_IFW_COMPONENT_${_CPACK_IFWCOMP_UNAME}_${_IFW_ARG_NAME}
+    _CPACK_IFWCOMP_STR)
+  endforeach()
+
+  if(CPack_CMake_INCLUDED)
+    file(APPEND "${CPACK_OUTPUT_CONFIG_FILE}" "${_CPACK_IFWCOMP_STR}")
+  endif()
+
+endmacro()
+
+# Macro for configure group
+macro(cpack_ifw_configure_component_group grpname)
+
+  string(TOUPPER ${grpname} _CPACK_IFWGRP_UNAME)
+
+  set(_IFW_OPT)
+  set(_IFW_ARGS NAME VERSION SCRIPT PRIORITY)
+  set(_IFW_MULTI_ARGS LICENSES)
+  cmake_parse_arguments(CPACK_IFW_COMPONENT_GROUP_${_CPACK_IFWGRP_UNAME} "${_IFW_OPT}" "${_IFW_ARGS}" "${_IFW_MULTI_ARGS}" ${ARGN})
+
+  _cpack_ifw_resolve_script(CPACK_IFW_COMPONENT_GROUP_${_CPACK_IFWGRP_UNAME}_SCRIPT)
+  _cpack_ifw_resolve_lisenses(CPACK_IFW_COMPONENT_GROUP_${_CPACK_IFWGRP_UNAME}_LICENSES)
+
+  set(_CPACK_IFWGRP_STR "\n# Configuration for IFW component group \"${grpname}\"\n")
+
+  foreach(_IFW_ARG_NAME ${_IFW_ARGS})
+  cpack_append_string_variable_set_command(
+    CPACK_IFW_COMPONENT_GROUP_${_CPACK_IFWGRP_UNAME}_${_IFW_ARG_NAME}
+    _CPACK_IFWGRP_STR)
+  endforeach()
+
+  foreach(_IFW_ARG_NAME ${_IFW_MULTI_ARGS})
+  cpack_append_variable_set_command(
+    CPACK_IFW_COMPONENT_GROUP_${_CPACK_IFWGRP_UNAME}_${_IFW_ARG_NAME}
+    _CPACK_IFWGRP_STR)
+  endforeach()
+
+  if(CPack_CMake_INCLUDED)
+    file(APPEND "${CPACK_OUTPUT_CONFIG_FILE}" "${_CPACK_IFWGRP_STR}")
+  endif()
+endmacro()
+
+# Macro for adding repository
+macro(cpack_ifw_add_repository reponame)
+
+  string(TOUPPER ${reponame} _CPACK_IFWREPO_UNAME)
+
+  set(_IFW_OPT DISABLED)
+  set(_IFW_ARGS URL USERNAME PASSWORD DISPLAY_NAME)
+  set(_IFW_MULTI_ARGS)
+  cmake_parse_arguments(CPACK_IFW_REPOSITORY_${_CPACK_IFWREPO_UNAME} "${_IFW_OPT}" "${_IFW_ARGS}" "${_IFW_MULTI_ARGS}" ${ARGN})
+
+  set(_CPACK_IFWREPO_STR "\n# Configuration for IFW repository \"${reponame}\"\n")
+
+  foreach(_IFW_ARG_NAME ${_IFW_OPT})
+  cpack_append_option_set_command(
+    CPACK_IFW_REPOSITORY_${_CPACK_IFWREPO_UNAME}_${_IFW_ARG_NAME}
+    _CPACK_IFWREPO_STR)
+  endforeach()
+
+  foreach(_IFW_ARG_NAME ${_IFW_ARGS})
+  cpack_append_string_variable_set_command(
+    CPACK_IFW_REPOSITORY_${_CPACK_IFWREPO_UNAME}_${_IFW_ARG_NAME}
+    _CPACK_IFWREPO_STR)
+  endforeach()
+
+  foreach(_IFW_ARG_NAME ${_IFW_MULTI_ARGS})
+  cpack_append_variable_set_command(
+    CPACK_IFW_REPOSITORY_${_CPACK_IFWREPO_UNAME}_${_IFW_ARG_NAME}
+    _CPACK_IFWREPO_STR)
+  endforeach()
+
+  list(APPEND CPACK_IFW_REPOSITORIES_ALL ${reponame})
+  set(_CPACK_IFWREPO_STR "${_CPACK_IFWREPO_STR}list(APPEND CPACK_IFW_REPOSITORIES_ALL ${reponame})\n")
+
+  if(CPack_CMake_INCLUDED)
+    file(APPEND "${CPACK_OUTPUT_CONFIG_FILE}" "${_CPACK_IFWREPO_STR}")
+  endif()
+
+endmacro()
+
+endif() # NOT CPackIFW_CMake_INCLUDED
diff --git a/Modules/CheckCCompilerFlag.cmake b/Modules/CheckCCompilerFlag.cmake
index efdac20..53f3454 100644
--- a/Modules/CheckCCompilerFlag.cmake
+++ b/Modules/CheckCCompilerFlag.cmake
@@ -10,6 +10,7 @@
 #
 #   <flag> - the compiler flag
 #   <var>  - variable to store the result
+#            Will be created as an internal cache variable.
 #
 # This internally calls the check_c_source_compiles macro and sets
 # CMAKE_REQUIRED_DEFINITIONS to <flag>.  See help for
diff --git a/Modules/CheckCSourceCompiles.cmake b/Modules/CheckCSourceCompiles.cmake
index 8721d55..6e80fb5 100644
--- a/Modules/CheckCSourceCompiles.cmake
+++ b/Modules/CheckCSourceCompiles.cmake
@@ -10,6 +10,7 @@
 #
 #   <code>       - source code to try to compile, must define 'main'
 #   <var>        - variable to store whether the source code compiled
+#                  Will be created as an internal cache variable.
 #   <fail-regex> - fail if test output matches this regex
 #
 # The following variables may be set before calling this macro to modify
@@ -39,7 +40,7 @@
 
 
 macro(CHECK_C_SOURCE_COMPILES SOURCE VAR)
-  if("${VAR}" MATCHES "^${VAR}$")
+  if(NOT DEFINED "${VAR}")
     set(_FAIL_REGEX)
     set(_key)
     foreach(arg ${ARGN})
diff --git a/Modules/CheckCSourceRuns.cmake b/Modules/CheckCSourceRuns.cmake
index a4fa57e..0ce423c 100644
--- a/Modules/CheckCSourceRuns.cmake
+++ b/Modules/CheckCSourceRuns.cmake
@@ -11,6 +11,7 @@
 #   <code>   - source code to try to compile
 #   <var>    - variable to store the result
 #              (1 for success, empty for failure)
+#              Will be created as an internal cache variable.
 #
 # The following variables may be set before calling this macro to modify
 # the way the check is run:
@@ -39,7 +40,7 @@
 
 
 macro(CHECK_C_SOURCE_RUNS SOURCE VAR)
-  if("${VAR}" MATCHES "^${VAR}$")
+  if(NOT DEFINED "${VAR}")
     set(MACRO_CHECK_FUNCTION_DEFINITIONS
       "-D${VAR} ${CMAKE_REQUIRED_FLAGS}")
     if(CMAKE_REQUIRED_LIBRARIES)
diff --git a/Modules/CheckCXXSourceCompiles.cmake b/Modules/CheckCXXSourceCompiles.cmake
index 6ce64a1..6d52ec6 100644
--- a/Modules/CheckCXXSourceCompiles.cmake
+++ b/Modules/CheckCXXSourceCompiles.cmake
@@ -10,6 +10,7 @@
 #
 #   <code>       - source code to try to compile, must define 'main'
 #   <var>        - variable to store whether the source code compiled
+#                  Will be created as an internal cache variable.
 #   <fail-regex> - fail if test output matches this regex
 #
 # The following variables may be set before calling this macro to modify
@@ -39,7 +40,7 @@
 
 
 macro(CHECK_CXX_SOURCE_COMPILES SOURCE VAR)
-  if("${VAR}" MATCHES "^${VAR}$")
+  if(NOT DEFINED "${VAR}")
     set(_FAIL_REGEX)
     set(_key)
     foreach(arg ${ARGN})
diff --git a/Modules/CheckCXXSourceRuns.cmake b/Modules/CheckCXXSourceRuns.cmake
index c655863..3c06d75 100644
--- a/Modules/CheckCXXSourceRuns.cmake
+++ b/Modules/CheckCXXSourceRuns.cmake
@@ -11,6 +11,7 @@
 #   <code>   - source code to try to compile
 #   <var>    - variable to store the result
 #              (1 for success, empty for failure)
+#              Will be created as an internal cache variable.
 #
 # The following variables may be set before calling this macro to modify
 # the way the check is run:
@@ -39,7 +40,7 @@
 
 
 macro(CHECK_CXX_SOURCE_RUNS SOURCE VAR)
-  if("${VAR}" MATCHES "^${VAR}$")
+  if(NOT DEFINED "${VAR}")
     set(MACRO_CHECK_FUNCTION_DEFINITIONS
       "-D${VAR} ${CMAKE_REQUIRED_FLAGS}")
     if(CMAKE_REQUIRED_LIBRARIES)
diff --git a/Modules/CheckFortranFunctionExists.cmake b/Modules/CheckFortranFunctionExists.cmake
index 0b12289..bd52f61 100644
--- a/Modules/CheckFortranFunctionExists.cmake
+++ b/Modules/CheckFortranFunctionExists.cmake
@@ -10,6 +10,7 @@
 #
 #   FUNCTION - the name of the Fortran function
 #   VARIABLE - variable to store the result
+#              Will be created as an internal cache variable.
 #
 #
 #
diff --git a/Modules/CheckFortranSourceCompiles.cmake b/Modules/CheckFortranSourceCompiles.cmake
new file mode 100644
index 0000000..f90d05b
--- /dev/null
+++ b/Modules/CheckFortranSourceCompiles.cmake
@@ -0,0 +1,111 @@
+#.rst:
+# CheckFortranSourceCompiles
+# --------------------------
+#
+# Check if given Fortran source compiles and links into an executable::
+#
+#   CHECK_Fortran_SOURCE_COMPILES(<code> <var> [FAIL_REGEX <fail-regex>])
+#
+# The arguments are:
+#
+# ``<code>``
+#   Source code to try to compile.  It must define a PROGRAM entry point.
+# ``<var>``
+#   Variable to store whether the source code compiled.
+#   Will be created as an internal cache variable.
+# ``<fail-regex>``
+#   Fail if test output matches this regex.
+#
+# The following variables may be set before calling this macro to modify
+# the way the check is run::
+#
+#   CMAKE_REQUIRED_FLAGS = string of compile command line flags
+#   CMAKE_REQUIRED_DEFINITIONS = list of macros to define (-DFOO=bar)
+#   CMAKE_REQUIRED_INCLUDES = list of include directories
+#   CMAKE_REQUIRED_LIBRARIES = list of libraries to link
+#   CMAKE_REQUIRED_QUIET = execute quietly without messages
+
+#=============================================================================
+# Copyright 2005-2009 Kitware, Inc.
+#
+# Distributed under the OSI-approved BSD License (the "License");
+# see accompanying file Copyright.txt for details.
+#
+# This software is distributed WITHOUT ANY WARRANTY; without even the
+# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+# See the License for more information.
+#=============================================================================
+# (To distribute this file outside of CMake, substitute the full
+#  License text for the above reference.)
+
+
+
+macro(CHECK_Fortran_SOURCE_COMPILES SOURCE VAR)
+  if(NOT DEFINED "${VAR}")
+    set(_FAIL_REGEX)
+    set(_key)
+    foreach(arg ${ARGN})
+      if("${arg}" MATCHES "^(FAIL_REGEX)$")
+        set(_key "${arg}")
+      elseif(_key)
+        list(APPEND _${_key} "${arg}")
+      else()
+        message(FATAL_ERROR "Unknown argument:\n  ${arg}\n")
+      endif()
+    endforeach()
+    set(MACRO_CHECK_FUNCTION_DEFINITIONS
+      "-D${VAR} ${CMAKE_REQUIRED_FLAGS}")
+    if(CMAKE_REQUIRED_LIBRARIES)
+      set(CHECK_Fortran_SOURCE_COMPILES_ADD_LIBRARIES
+        LINK_LIBRARIES ${CMAKE_REQUIRED_LIBRARIES})
+    else()
+      set(CHECK_Fortran_SOURCE_COMPILES_ADD_LIBRARIES)
+    endif()
+    if(CMAKE_REQUIRED_INCLUDES)
+      set(CHECK_Fortran_SOURCE_COMPILES_ADD_INCLUDES
+        "-DINCLUDE_DIRECTORIES:STRING=${CMAKE_REQUIRED_INCLUDES}")
+    else()
+      set(CHECK_Fortran_SOURCE_COMPILES_ADD_INCLUDES)
+    endif()
+    file(WRITE "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/src.F"
+      "${SOURCE}\n")
+
+    if(NOT CMAKE_REQUIRED_QUIET)
+      message(STATUS "Performing Test ${VAR}")
+    endif()
+    try_compile(${VAR}
+      ${CMAKE_BINARY_DIR}
+      ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/src.F
+      COMPILE_DEFINITIONS ${CMAKE_REQUIRED_DEFINITIONS}
+      ${CHECK_Fortran_SOURCE_COMPILES_ADD_LIBRARIES}
+      CMAKE_FLAGS -DCOMPILE_DEFINITIONS:STRING=${MACRO_CHECK_FUNCTION_DEFINITIONS}
+      "${CHECK_Fortran_SOURCE_COMPILES_ADD_INCLUDES}"
+      OUTPUT_VARIABLE OUTPUT)
+
+    foreach(_regex ${_FAIL_REGEX})
+      if("${OUTPUT}" MATCHES "${_regex}")
+        set(${VAR} 0)
+      endif()
+    endforeach()
+
+    if(${VAR})
+      set(${VAR} 1 CACHE INTERNAL "Test ${VAR}")
+      if(NOT CMAKE_REQUIRED_QUIET)
+        message(STATUS "Performing Test ${VAR} - Success")
+      endif()
+      file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeOutput.log
+        "Performing Fortran SOURCE FILE Test ${VAR} succeded with the following output:\n"
+        "${OUTPUT}\n"
+        "Source file was:\n${SOURCE}\n")
+    else()
+      if(NOT CMAKE_REQUIRED_QUIET)
+        message(STATUS "Performing Test ${VAR} - Failed")
+      endif()
+      set(${VAR} "" CACHE INTERNAL "Test ${VAR}")
+      file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log
+        "Performing Fortran SOURCE FILE Test ${VAR} failed with the following output:\n"
+        "${OUTPUT}\n"
+        "Source file was:\n${SOURCE}\n")
+    endif()
+  endif()
+endmacro()
diff --git a/Modules/CheckFunctionExists.cmake b/Modules/CheckFunctionExists.cmake
index bfd1836..d277c32 100644
--- a/Modules/CheckFunctionExists.cmake
+++ b/Modules/CheckFunctionExists.cmake
@@ -10,6 +10,7 @@
 # store the result in a <variable>.  This does not verify that any
 # system header file declares the function, only that it can be found at
 # link time (consider using CheckSymbolExists).
+# <variable> will be created as an internal cache variable.
 #
 # The following variables may be set before calling this macro to modify
 # the way the check is run:
@@ -38,7 +39,7 @@
 
 
 macro(CHECK_FUNCTION_EXISTS FUNCTION VARIABLE)
-  if("${VARIABLE}" MATCHES "^${VARIABLE}$")
+  if(NOT DEFINED "${VARIABLE}" OR "x${${VARIABLE}}" STREQUAL "x${VARIABLE}")
     set(MACRO_CHECK_FUNCTION_DEFINITIONS
       "-DCHECK_FUNCTION_EXISTS=${FUNCTION} ${CMAKE_REQUIRED_FLAGS}")
     if(NOT CMAKE_REQUIRED_QUIET)
diff --git a/Modules/CheckIncludeFile.cmake b/Modules/CheckIncludeFile.cmake
index ea73267..402b37c 100644
--- a/Modules/CheckIncludeFile.cmake
+++ b/Modules/CheckIncludeFile.cmake
@@ -10,6 +10,7 @@
 #
 #   INCLUDE  - name of include file
 #   VARIABLE - variable to return result
+#              Will be created as an internal cache variable.
 #
 #
 #
@@ -40,7 +41,7 @@
 #  License text for the above reference.)
 
 macro(CHECK_INCLUDE_FILE INCLUDE VARIABLE)
-  if("${VARIABLE}" MATCHES "^${VARIABLE}$")
+  if(NOT DEFINED "${VARIABLE}")
     if(CMAKE_REQUIRED_INCLUDES)
       set(CHECK_INCLUDE_FILE_C_INCLUDE_DIRS "-DINCLUDE_DIRECTORIES=${CMAKE_REQUIRED_INCLUDES}")
     else()
diff --git a/Modules/CheckIncludeFileCXX.cmake b/Modules/CheckIncludeFileCXX.cmake
index 39abeff..eae1730 100644
--- a/Modules/CheckIncludeFileCXX.cmake
+++ b/Modules/CheckIncludeFileCXX.cmake
@@ -14,6 +14,7 @@
 #
 #   INCLUDE  - name of include file
 #   VARIABLE - variable to return result
+#              Will be created as an internal cache variable.
 #
 #
 #
@@ -44,7 +45,7 @@
 #  License text for the above reference.)
 
 macro(CHECK_INCLUDE_FILE_CXX INCLUDE VARIABLE)
-  if("${VARIABLE}" MATCHES "^${VARIABLE}$")
+  if(NOT DEFINED "${VARIABLE}" OR "x${${VARIABLE}}" STREQUAL "x${VARIABLE}")
     if(CMAKE_REQUIRED_INCLUDES)
       set(CHECK_INCLUDE_FILE_CXX_INCLUDE_DIRS "-DINCLUDE_DIRECTORIES=${CMAKE_REQUIRED_INCLUDES}")
     else()
diff --git a/Modules/CheckIncludeFiles.cmake b/Modules/CheckIncludeFiles.cmake
index 6aa0f2b..2494862 100644
--- a/Modules/CheckIncludeFiles.cmake
+++ b/Modules/CheckIncludeFiles.cmake
@@ -12,6 +12,7 @@
 #
 #   INCLUDE  - list of files to include
 #   VARIABLE - variable to return result
+#              Will be created as an internal cache variable.
 #
 #
 #
@@ -39,7 +40,7 @@
 #  License text for the above reference.)
 
 macro(CHECK_INCLUDE_FILES INCLUDE VARIABLE)
-  if("${VARIABLE}" MATCHES "^${VARIABLE}$")
+  if(NOT DEFINED "${VARIABLE}")
     set(CMAKE_CONFIGURABLE_FILE_CONTENT "/* */\n")
     if(CMAKE_REQUIRED_INCLUDES)
       set(CHECK_INCLUDE_FILES_INCLUDE_DIRS "-DINCLUDE_DIRECTORIES=${CMAKE_REQUIRED_INCLUDES}")
@@ -53,7 +54,7 @@
         "${CMAKE_CONFIGURABLE_FILE_CONTENT}#include <${FILE}>\n")
     endforeach()
     set(CMAKE_CONFIGURABLE_FILE_CONTENT
-      "${CMAKE_CONFIGURABLE_FILE_CONTENT}\n\nint main(){return 0;}\n")
+      "${CMAKE_CONFIGURABLE_FILE_CONTENT}\n\nint main(void){return 0;}\n")
     configure_file("${CMAKE_ROOT}/Modules/CMakeConfigurableFile.in"
       "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/CheckIncludeFiles.c" @ONLY)
 
diff --git a/Modules/CheckLibraryExists.cmake b/Modules/CheckLibraryExists.cmake
index 2b41379..95c595a 100644
--- a/Modules/CheckLibraryExists.cmake
+++ b/Modules/CheckLibraryExists.cmake
@@ -12,6 +12,7 @@
 #   FUNCTION - the name of the function
 #   LOCATION - location where the library should be found
 #   VARIABLE - variable to store the result
+#              Will be created as an internal cache variable.
 #
 #
 #
@@ -41,7 +42,7 @@
 
 
 macro(CHECK_LIBRARY_EXISTS LIBRARY FUNCTION LOCATION VARIABLE)
-  if("${VARIABLE}" MATCHES "^${VARIABLE}$")
+  if(NOT DEFINED "${VARIABLE}")
     set(MACRO_CHECK_LIBRARY_EXISTS_DEFINITION
       "-DCHECK_FUNCTION_EXISTS=${FUNCTION} ${CMAKE_REQUIRED_FLAGS}")
     if(NOT CMAKE_REQUIRED_QUIET)
diff --git a/Modules/CheckPrototypeDefinition.cmake b/Modules/CheckPrototypeDefinition.cmake
index fe00074..e203d4c 100644
--- a/Modules/CheckPrototypeDefinition.cmake
+++ b/Modules/CheckPrototypeDefinition.cmake
@@ -13,6 +13,7 @@
 #   RETURN - The return value of the function.
 #   HEADER - The header files required.
 #   VARIABLE - The variable to store the result.
+#              Will be created as an internal cache variable.
 #
 # Example:
 #
@@ -56,7 +57,7 @@
 
 function(CHECK_PROTOTYPE_DEFINITION _FUNCTION _PROTOTYPE _RETURN _HEADER _VARIABLE)
 
-  if ("${_VARIABLE}" MATCHES "^${_VARIABLE}$")
+  if (NOT DEFINED ${_VARIABLE})
     set(CHECK_PROTOTYPE_DEFINITION_CONTENT "/* */\n")
 
     set(CHECK_PROTOTYPE_DEFINITION_FLAGS ${CMAKE_REQUIRED_FLAGS})
diff --git a/Modules/CheckStructHasMember.cmake b/Modules/CheckStructHasMember.cmake
index 880a688..c8949cf 100644
--- a/Modules/CheckStructHasMember.cmake
+++ b/Modules/CheckStructHasMember.cmake
@@ -70,7 +70,7 @@
 int main()
 {
    ${_STRUCT}* tmp;
-   tmp->${_MEMBER};
+   (void) tmp->${_MEMBER};
    return 0;
 }
 ")
diff --git a/Modules/CheckSymbolExists.cmake b/Modules/CheckSymbolExists.cmake
index bf2e797..79c5ba7 100644
--- a/Modules/CheckSymbolExists.cmake
+++ b/Modules/CheckSymbolExists.cmake
@@ -9,6 +9,7 @@
 # Check that the <symbol> is available after including given header
 # <files> and store the result in a <variable>.  Specify the list of
 # files in one argument as a semicolon-separated list.
+# <variable> will be created as an internal cache variable.
 #
 # If the header files define the symbol as a macro it is considered
 # available and assumed to work.  If the header files declare the symbol
@@ -50,7 +51,7 @@
 endmacro()
 
 macro(_CHECK_SYMBOL_EXISTS SOURCEFILE SYMBOL FILES VARIABLE)
-  if("${VARIABLE}" MATCHES "^${VARIABLE}$")
+  if(NOT DEFINED "${VARIABLE}" OR "x${${VARIABLE}}" STREQUAL "x${VARIABLE}")
     set(CMAKE_CONFIGURABLE_FILE_CONTENT "/* */\n")
     set(MACRO_CHECK_SYMBOL_EXISTS_FLAGS ${CMAKE_REQUIRED_FLAGS})
     if(CMAKE_REQUIRED_LIBRARIES)
diff --git a/Modules/CheckTypeSize.cmake b/Modules/CheckTypeSize.cmake
index 8ce6b88..73ad86e 100644
--- a/Modules/CheckTypeSize.cmake
+++ b/Modules/CheckTypeSize.cmake
@@ -19,6 +19,9 @@
 #    "0"    = type has arch-dependent size (see below)
 #    ""     = type does not exist
 #
+# Both ``HAVE_${VARIABLE}`` and ``${VARIABLE}`` will be created as internal
+# cache variables.
+#
 # Furthermore, the variable "${VARIABLE}_CODE" holds C preprocessor code
 # to define the macro "${VARIABLE}" to the size of the type, or leave
 # the macro undefined if the type does not exist.
diff --git a/Modules/CheckVariableExists.cmake b/Modules/CheckVariableExists.cmake
index 3a7ef13..f3e05e4 100644
--- a/Modules/CheckVariableExists.cmake
+++ b/Modules/CheckVariableExists.cmake
@@ -14,7 +14,7 @@
 #
 #   VAR      - the name of the variable
 #   VARIABLE - variable to store the result
-#
+#              Will be created as an internal cache variable.
 #
 #
 # This macro is only for C variables.
@@ -45,7 +45,7 @@
 
 
 macro(CHECK_VARIABLE_EXISTS VAR VARIABLE)
-  if("${VARIABLE}" MATCHES "^${VARIABLE}$")
+  if(NOT DEFINED "${VARIABLE}")
     set(MACRO_CHECK_VARIABLE_DEFINITIONS
       "-DCHECK_VARIABLE_EXISTS=${VAR} ${CMAKE_REQUIRED_FLAGS}")
     if(NOT CMAKE_REQUIRED_QUIET)
diff --git a/Modules/Compiler/ADSP-DetermineCompiler.cmake b/Modules/Compiler/ADSP-DetermineCompiler.cmake
index 0b5af0d..0340f69 100644
--- a/Modules/Compiler/ADSP-DetermineCompiler.cmake
+++ b/Modules/Compiler/ADSP-DetermineCompiler.cmake
@@ -4,7 +4,7 @@
 set(_compiler_id_version_compute "
 #if defined(__VISUALDSPVERSION__)
   /* __VISUALDSPVERSION__ = 0xVVRRPP00 */
-# define @PREFIX@COMPILER_VERSION_MAJOR HEX(__VISUALDSPVERSION__>>24)
-# define @PREFIX@COMPILER_VERSION_MINOR HEX(__VISUALDSPVERSION__>>16 & 0xFF)
-# define @PREFIX@COMPILER_VERSION_PATCH HEX(__VISUALDSPVERSION__>>8  & 0xFF)
+# define @PREFIX@COMPILER_VERSION_MAJOR @MACRO_HEX@(__VISUALDSPVERSION__>>24)
+# define @PREFIX@COMPILER_VERSION_MINOR @MACRO_HEX@(__VISUALDSPVERSION__>>16 & 0xFF)
+# define @PREFIX@COMPILER_VERSION_PATCH @MACRO_HEX@(__VISUALDSPVERSION__>>8  & 0xFF)
 #endif")
diff --git a/Modules/Compiler/AppleClang-DetermineCompiler.cmake b/Modules/Compiler/AppleClang-DetermineCompiler.cmake
index d293b7b..397f95c 100644
--- a/Modules/Compiler/AppleClang-DetermineCompiler.cmake
+++ b/Modules/Compiler/AppleClang-DetermineCompiler.cmake
@@ -4,4 +4,4 @@
 include("${CMAKE_CURRENT_LIST_DIR}/Clang-DetermineCompilerInternal.cmake")
 
 set(_compiler_id_version_compute "${_compiler_id_version_compute}
-# define @PREFIX@COMPILER_VERSION_TWEAK DEC(__apple_build_version__)")
+# define @PREFIX@COMPILER_VERSION_TWEAK @MACRO_DEC@(__apple_build_version__)")
diff --git a/Modules/Compiler/Borland-DetermineCompiler.cmake b/Modules/Compiler/Borland-DetermineCompiler.cmake
index 2e8a948..ef3083b 100644
--- a/Modules/Compiler/Borland-DetermineCompiler.cmake
+++ b/Modules/Compiler/Borland-DetermineCompiler.cmake
@@ -3,5 +3,5 @@
 
 set(_compiler_id_version_compute "
   /* __BORLANDC__ = 0xVRR */
-# define @PREFIX@COMPILER_VERSION_MAJOR HEX(__BORLANDC__>>8)
-# define @PREFIX@COMPILER_VERSION_MINOR HEX(__BORLANDC__ & 0xFF)")
+# define @PREFIX@COMPILER_VERSION_MAJOR @MACRO_HEX@(__BORLANDC__>>8)
+# define @PREFIX@COMPILER_VERSION_MINOR @MACRO_HEX@(__BORLANDC__ & 0xFF)")
diff --git a/Modules/Compiler/Clang-CXX.cmake b/Modules/Compiler/Clang-CXX.cmake
index bdb6d69..5dd7b4a 100644
--- a/Modules/Compiler/Clang-CXX.cmake
+++ b/Modules/Compiler/Clang-CXX.cmake
@@ -23,9 +23,12 @@
   set(CMAKE_CXX11_EXTENSION_COMPILE_OPTION "-std=gnu++0x")
 endif()
 
-if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 3.4)
-  set(CMAKE_CXX11_STANDARD_COMPILE_OPTION "-std=c++1y")
-  set(CMAKE_CXX11_EXTENSION_COMPILE_OPTION "-std=gnu++1y")
+if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 3.5)
+  set(CMAKE_CXX14_STANDARD_COMPILE_OPTION "-std=c++14")
+  set(CMAKE_CXX14_EXTENSION_COMPILE_OPTION "-std=gnu++14")
+elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 3.4)
+  set(CMAKE_CXX14_STANDARD_COMPILE_OPTION "-std=c++1y")
+  set(CMAKE_CXX14_EXTENSION_COMPILE_OPTION "-std=gnu++1y")
 endif()
 
 set(CMAKE_CXX_STANDARD_DEFAULT 98)
diff --git a/Modules/Compiler/Clang-DetermineCompilerInternal.cmake b/Modules/Compiler/Clang-DetermineCompilerInternal.cmake
index 9a37a63..08c1230 100644
--- a/Modules/Compiler/Clang-DetermineCompilerInternal.cmake
+++ b/Modules/Compiler/Clang-DetermineCompilerInternal.cmake
@@ -1,11 +1,15 @@
 
 set(_compiler_id_version_compute "
-# define @PREFIX@COMPILER_VERSION_MAJOR DEC(__clang_major__)
-# define @PREFIX@COMPILER_VERSION_MINOR DEC(__clang_minor__)
-# define @PREFIX@COMPILER_VERSION_PATCH DEC(__clang_patchlevel__)
+# define @PREFIX@COMPILER_VERSION_MAJOR @MACRO_DEC@(__clang_major__)
+# define @PREFIX@COMPILER_VERSION_MINOR @MACRO_DEC@(__clang_minor__)
+# define @PREFIX@COMPILER_VERSION_PATCH @MACRO_DEC@(__clang_patchlevel__)
+# if defined(_MSC_VER)
+   /* _MSC_VER = VVRR */
+#  define @PREFIX@SIMULATE_VERSION_MAJOR @MACRO_DEC@(_MSC_VER / 100)
+#  define @PREFIX@SIMULATE_VERSION_MINOR @MACRO_DEC@(_MSC_VER % 100)
+# endif")
+
+set(_compiler_id_simulate "
 # if defined(_MSC_VER)
 #  define @PREFIX@SIMULATE_ID \"MSVC\"
-   /* _MSC_VER = VVRR */
-#  define @PREFIX@SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100)
-#  define @PREFIX@SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100)
 # endif")
diff --git a/Modules/Compiler/Comeau-CXX-DetermineCompiler.cmake b/Modules/Compiler/Comeau-CXX-DetermineCompiler.cmake
index e4def4d..2265e5e 100644
--- a/Modules/Compiler/Comeau-CXX-DetermineCompiler.cmake
+++ b/Modules/Compiler/Comeau-CXX-DetermineCompiler.cmake
@@ -3,5 +3,5 @@
 
 set(_compiler_id_version_compute "
   /* __COMO_VERSION__ = VRR */
-# define @PREFIX@COMPILER_VERSION_MAJOR DEC(__COMO_VERSION__ / 100)
-# define @PREFIX@COMPILER_VERSION_MINOR DEC(__COMO_VERSION__ % 100)")
+# define @PREFIX@COMPILER_VERSION_MAJOR @MACRO_DEC@(__COMO_VERSION__ / 100)
+# define @PREFIX@COMPILER_VERSION_MINOR @MACRO_DEC@(__COMO_VERSION__ % 100)")
diff --git a/Modules/Compiler/Compaq-C-DetermineCompiler.cmake b/Modules/Compiler/Compaq-C-DetermineCompiler.cmake
index 56fedb1..02e99dc 100644
--- a/Modules/Compiler/Compaq-C-DetermineCompiler.cmake
+++ b/Modules/Compiler/Compaq-C-DetermineCompiler.cmake
@@ -3,6 +3,6 @@
 
 set(_compiler_id_version_compute "
   /* __DECC_VER = VVRRTPPPP */
-# define @PREFIX@COMPILER_VERSION_MAJOR DEC(__DECC_VER/10000000)
-# define @PREFIX@COMPILER_VERSION_MINOR DEC(__DECC_VER/100000  % 100)
-# define @PREFIX@COMPILER_VERSION_PATCH DEC(__DECC_VER         % 10000)")
+# define @PREFIX@COMPILER_VERSION_MAJOR @MACRO_DEC@(__DECC_VER/10000000)
+# define @PREFIX@COMPILER_VERSION_MINOR @MACRO_DEC@(__DECC_VER/100000  % 100)
+# define @PREFIX@COMPILER_VERSION_PATCH @MACRO_DEC@(__DECC_VER         % 10000)")
diff --git a/Modules/Compiler/Compaq-CXX-DetermineCompiler.cmake b/Modules/Compiler/Compaq-CXX-DetermineCompiler.cmake
index 5855c24..c7d0565 100644
--- a/Modules/Compiler/Compaq-CXX-DetermineCompiler.cmake
+++ b/Modules/Compiler/Compaq-CXX-DetermineCompiler.cmake
@@ -3,6 +3,6 @@
 
 set(_compiler_id_version_compute "
   /* __DECCXX_VER = VVRRTPPPP */
-# define @PREFIX@COMPILER_VERSION_MAJOR DEC(__DECCXX_VER/10000000)
-# define @PREFIX@COMPILER_VERSION_MINOR DEC(__DECCXX_VER/100000  % 100)
-# define @PREFIX@COMPILER_VERSION_PATCH DEC(__DECCXX_VER         % 10000)")
+# define @PREFIX@COMPILER_VERSION_MAJOR @MACRO_DEC@(__DECCXX_VER/10000000)
+# define @PREFIX@COMPILER_VERSION_MINOR @MACRO_DEC@(__DECCXX_VER/100000  % 100)
+# define @PREFIX@COMPILER_VERSION_PATCH @MACRO_DEC@(__DECCXX_VER         % 10000)")
diff --git a/Modules/Compiler/Cray-DetermineCompiler.cmake b/Modules/Compiler/Cray-DetermineCompiler.cmake
index 6e4eaf9..881b82c 100644
--- a/Modules/Compiler/Cray-DetermineCompiler.cmake
+++ b/Modules/Compiler/Cray-DetermineCompiler.cmake
@@ -2,5 +2,5 @@
 set(_compiler_id_pp_test "defined(_CRAYC)")
 
 set(_compiler_id_version_compute "
-# define @PREFIX@COMPILER_VERSION_MAJOR DEC(_RELEASE)
-# define @PREFIX@COMPILER_VERSION_MINOR DEC(_RELEASE_MINOR)")
+# define @PREFIX@COMPILER_VERSION_MAJOR @MACRO_DEC@(_RELEASE)
+# define @PREFIX@COMPILER_VERSION_MINOR @MACRO_DEC@(_RELEASE_MINOR)")
diff --git a/Modules/Compiler/Embarcadero-DetermineCompiler.cmake b/Modules/Compiler/Embarcadero-DetermineCompiler.cmake
index f52d79b..2feedac 100644
--- a/Modules/Compiler/Embarcadero-DetermineCompiler.cmake
+++ b/Modules/Compiler/Embarcadero-DetermineCompiler.cmake
@@ -2,6 +2,6 @@
 set(_compiler_id_pp_test "defined(__BORLANDC__) && defined(__CODEGEARC_VERSION__)")
 
 set(_compiler_id_version_compute "
-# define @PREFIX@COMPILER_VERSION_MAJOR HEX(__CODEGEARC_VERSION__>>24 & 0x00FF)
-# define @PREFIX@COMPILER_VERSION_MINOR HEX(__CODEGEARC_VERSION__>>16 & 0x00FF)
-# define @PREFIX@COMPILER_VERSION_PATCH HEX(__CODEGEARC_VERSION__     & 0xFFFF)")
+# define @PREFIX@COMPILER_VERSION_MAJOR @MACRO_HEX@(__CODEGEARC_VERSION__>>24 & 0x00FF)
+# define @PREFIX@COMPILER_VERSION_MINOR @MACRO_HEX@(__CODEGEARC_VERSION__>>16 & 0x00FF)
+# define @PREFIX@COMPILER_VERSION_PATCH @MACRO_HEX@(__CODEGEARC_VERSION__     & 0xFFFF)")
diff --git a/Modules/Compiler/Fujitsu-DetermineCompiler.cmake b/Modules/Compiler/Fujitsu-DetermineCompiler.cmake
new file mode 100644
index 0000000..73ee38c
--- /dev/null
+++ b/Modules/Compiler/Fujitsu-DetermineCompiler.cmake
@@ -0,0 +1,2 @@
+
+set(_compiler_id_pp_test "defined(__FUJITSU) || defined(__FCC_VERSION) || defined(__fcc_version)")
diff --git a/Modules/Compiler/GNU-DetermineCompiler.cmake b/Modules/Compiler/GNU-DetermineCompiler.cmake
index f0c25dd..261f148 100644
--- a/Modules/Compiler/GNU-DetermineCompiler.cmake
+++ b/Modules/Compiler/GNU-DetermineCompiler.cmake
@@ -2,8 +2,8 @@
 set(_compiler_id_pp_test "defined(__GNUC__)")
 
 set(_compiler_id_version_compute "
-# define @PREFIX@COMPILER_VERSION_MAJOR DEC(__GNUC__)
-# define @PREFIX@COMPILER_VERSION_MINOR DEC(__GNUC_MINOR__)
+# define @PREFIX@COMPILER_VERSION_MAJOR @MACRO_DEC@(__GNUC__)
+# define @PREFIX@COMPILER_VERSION_MINOR @MACRO_DEC@(__GNUC_MINOR__)
 # if defined(__GNUC_PATCHLEVEL__)
-#  define @PREFIX@COMPILER_VERSION_PATCH DEC(__GNUC_PATCHLEVEL__)
+#  define @PREFIX@COMPILER_VERSION_PATCH @MACRO_DEC@(__GNUC_PATCHLEVEL__)
 # endif")
diff --git a/Modules/Compiler/HP-C-DetermineCompiler.cmake b/Modules/Compiler/HP-C-DetermineCompiler.cmake
index 024a658..4269799 100644
--- a/Modules/Compiler/HP-C-DetermineCompiler.cmake
+++ b/Modules/Compiler/HP-C-DetermineCompiler.cmake
@@ -3,6 +3,6 @@
 
 set(_compiler_id_version_compute "
   /* __HP_cc = VVRRPP */
-# define @PREFIX@COMPILER_VERSION_MAJOR DEC(__HP_cc/10000)
-# define @PREFIX@COMPILER_VERSION_MINOR DEC(__HP_cc/100 % 100)
-# define @PREFIX@COMPILER_VERSION_PATCH DEC(__HP_cc     % 100)")
+# define @PREFIX@COMPILER_VERSION_MAJOR @MACRO_DEC@(__HP_cc/10000)
+# define @PREFIX@COMPILER_VERSION_MINOR @MACRO_DEC@(__HP_cc/100 % 100)
+# define @PREFIX@COMPILER_VERSION_PATCH @MACRO_DEC@(__HP_cc     % 100)")
diff --git a/Modules/Compiler/HP-CXX-DetermineCompiler.cmake b/Modules/Compiler/HP-CXX-DetermineCompiler.cmake
index 6999492..3d4d7e4 100644
--- a/Modules/Compiler/HP-CXX-DetermineCompiler.cmake
+++ b/Modules/Compiler/HP-CXX-DetermineCompiler.cmake
@@ -3,6 +3,6 @@
 
 set(_compiler_id_version_compute "
   /* __HP_aCC = VVRRPP */
-# define @PREFIX@COMPILER_VERSION_MAJOR DEC(__HP_aCC/10000)
-# define @PREFIX@COMPILER_VERSION_MINOR DEC(__HP_aCC/100 % 100)
-# define @PREFIX@COMPILER_VERSION_PATCH DEC(__HP_aCC     % 100)")
+# define @PREFIX@COMPILER_VERSION_MAJOR @MACRO_DEC@(__HP_aCC/10000)
+# define @PREFIX@COMPILER_VERSION_MINOR @MACRO_DEC@(__HP_aCC/100 % 100)
+# define @PREFIX@COMPILER_VERSION_PATCH @MACRO_DEC@(__HP_aCC     % 100)")
diff --git a/Modules/Compiler/IBMCPP-C-DetermineVersionInternal.cmake b/Modules/Compiler/IBMCPP-C-DetermineVersionInternal.cmake
index 6169ab4..899e284 100644
--- a/Modules/Compiler/IBMCPP-C-DetermineVersionInternal.cmake
+++ b/Modules/Compiler/IBMCPP-C-DetermineVersionInternal.cmake
@@ -1,6 +1,6 @@
 
 set(_compiler_id_version_compute "
   /* __IBMC__ = VRP */
-# define @PREFIX@COMPILER_VERSION_MAJOR DEC(__IBMC__/100)
-# define @PREFIX@COMPILER_VERSION_MINOR DEC(__IBMC__/10 % 10)
-# define @PREFIX@COMPILER_VERSION_PATCH DEC(__IBMC__    % 10)")
+# define @PREFIX@COMPILER_VERSION_MAJOR @MACRO_DEC@(__IBMC__/100)
+# define @PREFIX@COMPILER_VERSION_MINOR @MACRO_DEC@(__IBMC__/10 % 10)
+# define @PREFIX@COMPILER_VERSION_PATCH @MACRO_DEC@(__IBMC__    % 10)")
diff --git a/Modules/Compiler/IBMCPP-CXX-DetermineVersionInternal.cmake b/Modules/Compiler/IBMCPP-CXX-DetermineVersionInternal.cmake
index f673d72..73aa2b4 100644
--- a/Modules/Compiler/IBMCPP-CXX-DetermineVersionInternal.cmake
+++ b/Modules/Compiler/IBMCPP-CXX-DetermineVersionInternal.cmake
@@ -1,6 +1,6 @@
 
 set(_compiler_id_version_compute "
   /* __IBMCPP__ = VRP */
-# define @PREFIX@COMPILER_VERSION_MAJOR DEC(__IBMCPP__/100)
-# define @PREFIX@COMPILER_VERSION_MINOR DEC(__IBMCPP__/10 % 10)
-# define @PREFIX@COMPILER_VERSION_PATCH DEC(__IBMCPP__    % 10)")
+# define @PREFIX@COMPILER_VERSION_MAJOR @MACRO_DEC@(__IBMCPP__/100)
+# define @PREFIX@COMPILER_VERSION_MINOR @MACRO_DEC@(__IBMCPP__/10 % 10)
+# define @PREFIX@COMPILER_VERSION_PATCH @MACRO_DEC@(__IBMCPP__    % 10)")
diff --git a/Modules/Compiler/Intel-DetermineCompiler.cmake b/Modules/Compiler/Intel-DetermineCompiler.cmake
index 6fada1c..d7e4532 100644
--- a/Modules/Compiler/Intel-DetermineCompiler.cmake
+++ b/Modules/Compiler/Intel-DetermineCompiler.cmake
@@ -3,20 +3,24 @@
 
 set(_compiler_id_version_compute "
   /* __INTEL_COMPILER = VRP */
-# define @PREFIX@COMPILER_VERSION_MAJOR DEC(__INTEL_COMPILER/100)
-# define @PREFIX@COMPILER_VERSION_MINOR DEC(__INTEL_COMPILER/10 % 10)
+# define @PREFIX@COMPILER_VERSION_MAJOR @MACRO_DEC@(__INTEL_COMPILER/100)
+# define @PREFIX@COMPILER_VERSION_MINOR @MACRO_DEC@(__INTEL_COMPILER/10 % 10)
 # if defined(__INTEL_COMPILER_UPDATE)
-#  define @PREFIX@COMPILER_VERSION_PATCH DEC(__INTEL_COMPILER_UPDATE)
+#  define @PREFIX@COMPILER_VERSION_PATCH @MACRO_DEC@(__INTEL_COMPILER_UPDATE)
 # else
-#  define @PREFIX@COMPILER_VERSION_PATCH DEC(__INTEL_COMPILER   % 10)
+#  define @PREFIX@COMPILER_VERSION_PATCH @MACRO_DEC@(__INTEL_COMPILER   % 10)
 # endif
 # if defined(__INTEL_COMPILER_BUILD_DATE)
   /* __INTEL_COMPILER_BUILD_DATE = YYYYMMDD */
-#  define @PREFIX@COMPILER_VERSION_TWEAK DEC(__INTEL_COMPILER_BUILD_DATE)
+#  define @PREFIX@COMPILER_VERSION_TWEAK @MACRO_DEC@(__INTEL_COMPILER_BUILD_DATE)
 # endif
 # if defined(_MSC_VER)
-#  define @PREFIX@SIMULATE_ID \"MSVC\"
    /* _MSC_VER = VVRR */
-#  define @PREFIX@SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100)
-#  define @PREFIX@SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100)
+#  define @PREFIX@SIMULATE_VERSION_MAJOR @MACRO_DEC@(_MSC_VER / 100)
+#  define @PREFIX@SIMULATE_VERSION_MINOR @MACRO_DEC@(_MSC_VER % 100)
+# endif")
+
+set(_compiler_id_simulate "
+# if defined(_MSC_VER)
+#  define @PREFIX@SIMULATE_ID \"MSVC\"
 # endif")
diff --git a/Modules/Compiler/MIPSpro-DetermineCompiler.cmake b/Modules/Compiler/MIPSpro-DetermineCompiler.cmake
index 31eb345..9e48553 100644
--- a/Modules/Compiler/MIPSpro-DetermineCompiler.cmake
+++ b/Modules/Compiler/MIPSpro-DetermineCompiler.cmake
@@ -4,12 +4,12 @@
 set(_compiler_id_version_compute "
 # if defined(_SGI_COMPILER_VERSION)
   /* _SGI_COMPILER_VERSION = VRP */
-#  define @PREFIX@COMPILER_VERSION_MAJOR DEC(_SGI_COMPILER_VERSION/100)
-#  define @PREFIX@COMPILER_VERSION_MINOR DEC(_SGI_COMPILER_VERSION/10 % 10)
-#  define @PREFIX@COMPILER_VERSION_PATCH DEC(_SGI_COMPILER_VERSION    % 10)
+#  define @PREFIX@COMPILER_VERSION_MAJOR @MACRO_DEC@(_SGI_COMPILER_VERSION/100)
+#  define @PREFIX@COMPILER_VERSION_MINOR @MACRO_DEC@(_SGI_COMPILER_VERSION/10 % 10)
+#  define @PREFIX@COMPILER_VERSION_PATCH @MACRO_DEC@(_SGI_COMPILER_VERSION    % 10)
 # else
   /* _COMPILER_VERSION = VRP */
-#  define @PREFIX@COMPILER_VERSION_MAJOR DEC(_COMPILER_VERSION/100)
-#  define @PREFIX@COMPILER_VERSION_MINOR DEC(_COMPILER_VERSION/10 % 10)
-#  define @PREFIX@COMPILER_VERSION_PATCH DEC(_COMPILER_VERSION    % 10)
+#  define @PREFIX@COMPILER_VERSION_MAJOR @MACRO_DEC@(_COMPILER_VERSION/100)
+#  define @PREFIX@COMPILER_VERSION_MINOR @MACRO_DEC@(_COMPILER_VERSION/10 % 10)
+#  define @PREFIX@COMPILER_VERSION_PATCH @MACRO_DEC@(_COMPILER_VERSION    % 10)
 # endif")
diff --git a/Modules/Compiler/MSVC-DetermineCompiler.cmake b/Modules/Compiler/MSVC-DetermineCompiler.cmake
index d462d07..313de89 100644
--- a/Modules/Compiler/MSVC-DetermineCompiler.cmake
+++ b/Modules/Compiler/MSVC-DetermineCompiler.cmake
@@ -3,17 +3,17 @@
 
 set(_compiler_id_version_compute "
   /* _MSC_VER = VVRR */
-# define @PREFIX@COMPILER_VERSION_MAJOR DEC(_MSC_VER / 100)
-# define @PREFIX@COMPILER_VERSION_MINOR DEC(_MSC_VER % 100)
+# define @PREFIX@COMPILER_VERSION_MAJOR @MACRO_DEC@(_MSC_VER / 100)
+# define @PREFIX@COMPILER_VERSION_MINOR @MACRO_DEC@(_MSC_VER % 100)
 # if defined(_MSC_FULL_VER)
 #  if _MSC_VER >= 1400
     /* _MSC_FULL_VER = VVRRPPPPP */
-#   define @PREFIX@COMPILER_VERSION_PATCH DEC(_MSC_FULL_VER % 100000)
+#   define @PREFIX@COMPILER_VERSION_PATCH @MACRO_DEC@(_MSC_FULL_VER % 100000)
 #  else
     /* _MSC_FULL_VER = VVRRPPPP */
-#   define @PREFIX@COMPILER_VERSION_PATCH DEC(_MSC_FULL_VER % 10000)
+#   define @PREFIX@COMPILER_VERSION_PATCH @MACRO_DEC@(_MSC_FULL_VER % 10000)
 #  endif
 # endif
 # if defined(_MSC_BUILD)
-#  define @PREFIX@COMPILER_VERSION_TWEAK DEC(_MSC_BUILD)
+#  define @PREFIX@COMPILER_VERSION_TWEAK @MACRO_DEC@(_MSC_BUILD)
 # endif")
diff --git a/Modules/Compiler/OpenWatcom-DetermineCompiler.cmake b/Modules/Compiler/OpenWatcom-DetermineCompiler.cmake
index 6d416c1..2ed116c 100644
--- a/Modules/Compiler/OpenWatcom-DetermineCompiler.cmake
+++ b/Modules/Compiler/OpenWatcom-DetermineCompiler.cmake
@@ -3,8 +3,8 @@
 
 set(_compiler_id_version_compute "
    /* __WATCOMC__ = VVRP + 1100 */
-# define @PREFIX@COMPILER_VERSION_MAJOR DEC((__WATCOMC__ - 1100) / 100)
-# define @PREFIX@COMPILER_VERSION_MINOR DEC((__WATCOMC__ / 10) % 10)
+# define @PREFIX@COMPILER_VERSION_MAJOR @MACRO_DEC@((__WATCOMC__ - 1100) / 100)
+# define @PREFIX@COMPILER_VERSION_MINOR @MACRO_DEC@((__WATCOMC__ / 10) % 10)
 # if (__WATCOMC__ % 10) > 0
-#  define @PREFIX@COMPILER_VERSION_PATCH DEC(__WATCOMC__ % 10)
+#  define @PREFIX@COMPILER_VERSION_PATCH @MACRO_DEC@(__WATCOMC__ % 10)
 # endif")
diff --git a/Modules/Compiler/PGI-DetermineCompiler.cmake b/Modules/Compiler/PGI-DetermineCompiler.cmake
index 8e68bd6..8d3dc9c 100644
--- a/Modules/Compiler/PGI-DetermineCompiler.cmake
+++ b/Modules/Compiler/PGI-DetermineCompiler.cmake
@@ -2,8 +2,8 @@
 set(_compiler_id_pp_test "defined(__PGI)")
 
 set(_compiler_id_version_compute "
-# define @PREFIX@COMPILER_VERSION_MAJOR DEC(__PGIC__)
-# define @PREFIX@COMPILER_VERSION_MINOR DEC(__PGIC_MINOR__)
+# define @PREFIX@COMPILER_VERSION_MAJOR @MACRO_DEC@(__PGIC__)
+# define @PREFIX@COMPILER_VERSION_MINOR @MACRO_DEC@(__PGIC_MINOR__)
 # if defined(__PGIC_PATCHLEVEL__)
-#  define @PREFIX@COMPILER_VERSION_PATCH DEC(__PGIC_PATCHLEVEL__)
+#  define @PREFIX@COMPILER_VERSION_PATCH @MACRO_DEC@(__PGIC_PATCHLEVEL__)
 # endif")
diff --git a/Modules/Compiler/PathScale-DetermineCompiler.cmake b/Modules/Compiler/PathScale-DetermineCompiler.cmake
index 3335e26..4eb81de 100644
--- a/Modules/Compiler/PathScale-DetermineCompiler.cmake
+++ b/Modules/Compiler/PathScale-DetermineCompiler.cmake
@@ -2,8 +2,8 @@
 set(_compiler_id_pp_test "defined(__PATHCC__)")
 
 set(_compiler_id_version_compute "
-# define @PREFIX@COMPILER_VERSION_MAJOR DEC(__PATHCC__)
-# define @PREFIX@COMPILER_VERSION_MINOR DEC(__PATHCC_MINOR__)
+# define @PREFIX@COMPILER_VERSION_MAJOR @MACRO_DEC@(__PATHCC__)
+# define @PREFIX@COMPILER_VERSION_MINOR @MACRO_DEC@(__PATHCC_MINOR__)
 # if defined(__PATHCC_PATCHLEVEL__)
-#  define @PREFIX@COMPILER_VERSION_PATCH DEC(__PATHCC_PATCHLEVEL__)
+#  define @PREFIX@COMPILER_VERSION_PATCH @MACRO_DEC@(__PATHCC_PATCHLEVEL__)
 # endif")
diff --git a/Modules/Compiler/QCC-C.cmake b/Modules/Compiler/QCC-C.cmake
new file mode 100644
index 0000000..ae4a2f4
--- /dev/null
+++ b/Modules/Compiler/QCC-C.cmake
@@ -0,0 +1,2 @@
+include(Compiler/QCC)
+__compiler_qcc(C)
diff --git a/Modules/Compiler/QCC-CXX.cmake b/Modules/Compiler/QCC-CXX.cmake
new file mode 100644
index 0000000..a676bbe
--- /dev/null
+++ b/Modules/Compiler/QCC-CXX.cmake
@@ -0,0 +1,12 @@
+include(Compiler/QCC)
+__compiler_qcc(CXX)
+
+# If the toolchain uses qcc for CMAKE_CXX_COMPILER instead of QCC, the
+# default for the driver is not c++.
+set(CMAKE_CXX_COMPILE_OBJECT
+  "<CMAKE_CXX_COMPILER> -lang-c++ <DEFINES> <FLAGS> -o <OBJECT> -c <SOURCE>")
+
+set(CMAKE_CXX_LINK_EXECUTABLE
+  "<CMAKE_CXX_COMPILER> -lang-c++ <FLAGS> <CMAKE_CXX_LINK_FLAGS> <LINK_FLAGS> <OBJECTS>  -o <TARGET> <LINK_LIBRARIES>")
+
+set(CMAKE_CXX_COMPILE_OPTIONS_VISIBILITY_INLINES_HIDDEN "-fvisibility-inlines-hidden")
diff --git a/Modules/Compiler/QCC.cmake b/Modules/Compiler/QCC.cmake
new file mode 100644
index 0000000..76477e4
--- /dev/null
+++ b/Modules/Compiler/QCC.cmake
@@ -0,0 +1,24 @@
+
+#=============================================================================
+# Copyright 2002-2014 Kitware, Inc.
+#
+# Distributed under the OSI-approved BSD License (the "License");
+# see accompanying file Copyright.txt for details.
+#
+# This software is distributed WITHOUT ANY WARRANTY; without even the
+# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+# See the License for more information.
+#=============================================================================
+# (To distribute this file outside of CMake, substitute the full
+#  License text for the above reference.)
+include(Compiler/GNU)
+
+macro(__compiler_qcc lang)
+  __compiler_gnu(${lang})
+
+  # http://www.qnx.com/developers/docs/6.4.0/neutrino/utilities/q/qcc.html#examples
+  set(CMAKE_${lang}_COMPILE_OPTIONS_TARGET "-V")
+
+  set(CMAKE_INCLUDE_SYSTEM_FLAG_${lang} "-Wp,-isystem,")
+  set(CMAKE_DEPFILE_FLAGS_${lang} "-Wc,-MMD,<DEPFILE>,-MT,<OBJECT>,-MF,<DEPFILE>")
+endmacro()
diff --git a/Modules/Compiler/SDCC-C-DetermineCompiler.cmake b/Modules/Compiler/SDCC-C-DetermineCompiler.cmake
index 8fe60d9..1d7dd78 100644
--- a/Modules/Compiler/SDCC-C-DetermineCompiler.cmake
+++ b/Modules/Compiler/SDCC-C-DetermineCompiler.cmake
@@ -5,6 +5,6 @@
 
 set(_compiler_id_version_compute "
   /* SDCC = VRP */
-#  define COMPILER_VERSION_MAJOR DEC(SDCC/100)
-#  define COMPILER_VERSION_MINOR DEC(SDCC/10 % 10)
-#  define COMPILER_VERSION_PATCH DEC(SDCC    % 10)")
+#  define COMPILER_VERSION_MAJOR @MACRO_DEC@(SDCC/100)
+#  define COMPILER_VERSION_MINOR @MACRO_DEC@(SDCC/10 % 10)
+#  define COMPILER_VERSION_PATCH @MACRO_DEC@(SDCC    % 10)")
diff --git a/Modules/Compiler/SunPro-C-DetermineCompiler.cmake b/Modules/Compiler/SunPro-C-DetermineCompiler.cmake
index 7db1a97..e9d7457 100644
--- a/Modules/Compiler/SunPro-C-DetermineCompiler.cmake
+++ b/Modules/Compiler/SunPro-C-DetermineCompiler.cmake
@@ -4,12 +4,12 @@
 set(_compiler_id_version_compute "
 # if __SUNPRO_C >= 0x5100
    /* __SUNPRO_C = 0xVRRP */
-#  define @PREFIX@COMPILER_VERSION_MAJOR HEX(__SUNPRO_C>>12)
-#  define @PREFIX@COMPILER_VERSION_MINOR HEX(__SUNPRO_C>>4 & 0xFF)
-#  define @PREFIX@COMPILER_VERSION_PATCH HEX(__SUNPRO_C    & 0xF)
+#  define @PREFIX@COMPILER_VERSION_MAJOR @MACRO_HEX@(__SUNPRO_C>>12)
+#  define @PREFIX@COMPILER_VERSION_MINOR @MACRO_HEX@(__SUNPRO_C>>4 & 0xFF)
+#  define @PREFIX@COMPILER_VERSION_PATCH @MACRO_HEX@(__SUNPRO_C    & 0xF)
 # else
    /* __SUNPRO_CC = 0xVRP */
-#  define @PREFIX@COMPILER_VERSION_MAJOR HEX(__SUNPRO_C>>8)
-#  define @PREFIX@COMPILER_VERSION_MINOR HEX(__SUNPRO_C>>4 & 0xF)
-#  define @PREFIX@COMPILER_VERSION_PATCH HEX(__SUNPRO_C    & 0xF)
+#  define @PREFIX@COMPILER_VERSION_MAJOR @MACRO_HEX@(__SUNPRO_C>>8)
+#  define @PREFIX@COMPILER_VERSION_MINOR @MACRO_HEX@(__SUNPRO_C>>4 & 0xF)
+#  define @PREFIX@COMPILER_VERSION_PATCH @MACRO_HEX@(__SUNPRO_C    & 0xF)
 # endif")
diff --git a/Modules/Compiler/SunPro-CXX-DetermineCompiler.cmake b/Modules/Compiler/SunPro-CXX-DetermineCompiler.cmake
index 0a48cc6..5c23a95 100644
--- a/Modules/Compiler/SunPro-CXX-DetermineCompiler.cmake
+++ b/Modules/Compiler/SunPro-CXX-DetermineCompiler.cmake
@@ -4,12 +4,12 @@
 set(_compiler_id_version_compute "
 # if __SUNPRO_CC >= 0x5100
    /* __SUNPRO_CC = 0xVRRP */
-#  define @PREFIX@COMPILER_VERSION_MAJOR HEX(__SUNPRO_CC>>12)
-#  define @PREFIX@COMPILER_VERSION_MINOR HEX(__SUNPRO_CC>>4 & 0xFF)
-#  define @PREFIX@COMPILER_VERSION_PATCH HEX(__SUNPRO_CC    & 0xF)
+#  define @PREFIX@COMPILER_VERSION_MAJOR @MACRO_HEX@(__SUNPRO_CC>>12)
+#  define @PREFIX@COMPILER_VERSION_MINOR @MACRO_HEX@(__SUNPRO_CC>>4 & 0xFF)
+#  define @PREFIX@COMPILER_VERSION_PATCH @MACRO_HEX@(__SUNPRO_CC    & 0xF)
 # else
    /* __SUNPRO_CC = 0xVRP */
-#  define @PREFIX@COMPILER_VERSION_MAJOR HEX(__SUNPRO_CC>>8)
-#  define @PREFIX@COMPILER_VERSION_MINOR HEX(__SUNPRO_CC>>4 & 0xF)
-#  define @PREFIX@COMPILER_VERSION_PATCH HEX(__SUNPRO_CC    & 0xF)
+#  define @PREFIX@COMPILER_VERSION_MAJOR @MACRO_HEX@(__SUNPRO_CC>>8)
+#  define @PREFIX@COMPILER_VERSION_MINOR @MACRO_HEX@(__SUNPRO_CC>>4 & 0xF)
+#  define @PREFIX@COMPILER_VERSION_PATCH @MACRO_HEX@(__SUNPRO_CC    & 0xF)
 # endif")
diff --git a/Modules/Compiler/TI-DetermineCompiler.cmake b/Modules/Compiler/TI-DetermineCompiler.cmake
index 1856c9b..19aa9e3 100644
--- a/Modules/Compiler/TI-DetermineCompiler.cmake
+++ b/Modules/Compiler/TI-DetermineCompiler.cmake
@@ -3,6 +3,6 @@
 
 set(_compiler_id_version_compute "
   /* __TI_COMPILER_VERSION__ = VVVRRRPPP */
-# define @PREFIX@COMPILER_VERSION_MAJOR DEC(__TI_COMPILER_VERSION__/1000000)
-# define @PREFIX@COMPILER_VERSION_MINOR DEC(__TI_COMPILER_VERSION__/1000   % 1000)
-# define @PREFIX@COMPILER_VERSION_PATCH DEC(__TI_COMPILER_VERSION__        % 1000)")
+# define @PREFIX@COMPILER_VERSION_MAJOR @MACRO_DEC@(__TI_COMPILER_VERSION__/1000000)
+# define @PREFIX@COMPILER_VERSION_MINOR @MACRO_DEC@(__TI_COMPILER_VERSION__/1000   % 1000)
+# define @PREFIX@COMPILER_VERSION_PATCH @MACRO_DEC@(__TI_COMPILER_VERSION__        % 1000)")
diff --git a/Modules/Compiler/Watcom-DetermineCompiler.cmake b/Modules/Compiler/Watcom-DetermineCompiler.cmake
index cc59abf..153e350 100644
--- a/Modules/Compiler/Watcom-DetermineCompiler.cmake
+++ b/Modules/Compiler/Watcom-DetermineCompiler.cmake
@@ -3,8 +3,8 @@
 
 set(_compiler_id_version_compute "
    /* __WATCOMC__ = VVRR */
-# define @PREFIX@COMPILER_VERSION_MAJOR DEC(__WATCOMC__ / 100)
-# define @PREFIX@COMPILER_VERSION_MINOR DEC((__WATCOMC__ / 10) % 10)
+# define @PREFIX@COMPILER_VERSION_MAJOR @MACRO_DEC@(__WATCOMC__ / 100)
+# define @PREFIX@COMPILER_VERSION_MINOR @MACRO_DEC@((__WATCOMC__ / 10) % 10)
 # if (__WATCOMC__ % 10) > 0
-#  define @PREFIX@COMPILER_VERSION_PATCH DEC(__WATCOMC__ % 10)
+#  define @PREFIX@COMPILER_VERSION_PATCH @MACRO_DEC@(__WATCOMC__ % 10)
 # endif")
diff --git a/Modules/CompilerId/VS-10.vcxproj.in b/Modules/CompilerId/VS-10.vcxproj.in
index 1a7a539..a17d03d 100644
--- a/Modules/CompilerId/VS-10.vcxproj.in
+++ b/Modules/CompilerId/VS-10.vcxproj.in
@@ -10,6 +10,9 @@
     <ProjectGuid>{CAE07175-D007-4FC3-BFE8-47B392814159}</ProjectGuid>
     <RootNamespace>CompilerId@id_lang@</RootNamespace>
     <Keyword>Win32Proj</Keyword>
+    @id_system@
+    @id_system_version@
+    @id_WindowsSDKDesktopARMSupport@
   </PropertyGroup>
   <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
   <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|@id_platform@'" Label="Configuration">
diff --git a/Modules/CompilerId/VS-NsightTegra.vcxproj.in b/Modules/CompilerId/VS-NsightTegra.vcxproj.in
new file mode 100644
index 0000000..b7389eb
--- /dev/null
+++ b/Modules/CompilerId/VS-NsightTegra.vcxproj.in
@@ -0,0 +1,56 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <PropertyGroup Label="NsightTegraProject">
+    <NsightTegraProjectRevisionNumber>6</NsightTegraProjectRevisionNumber>
+  </PropertyGroup>
+  <ItemGroup Label="ProjectConfigurations">
+    <ProjectConfiguration Include="Debug|@id_platform@">
+      <Configuration>Debug</Configuration>
+      <Platform>@id_platform@</Platform>
+    </ProjectConfiguration>
+  </ItemGroup>
+  <PropertyGroup Label="Globals">
+    <ProjectGuid>{CAE07175-D007-4FC3-BFE8-47B392814159}</ProjectGuid>
+    <RootNamespace>CompilerId@id_lang@</RootNamespace>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|@id_platform@'" Label="Configuration">
+    <ConfigurationType>StaticLibrary</ConfigurationType>
+    @id_toolset@
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <PropertyGroup>
+    <_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
+    <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|@id_platform@'">.\</OutDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|@id_platform@'">$(Configuration)\</IntDir>
+    <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|@id_platform@'">false</LinkIncremental>
+  </PropertyGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|@id_platform@'">
+    <ClCompile>
+      <PreprocessorDefinitions>%(PreprocessorDefinitions)</PreprocessorDefinitions>
+    </ClCompile>
+    <Link>
+    </Link>
+    <PostBuildEvent>
+      <Command>
+if "$(ToolchainName)"=="gcc" (
+  for %%i in ($(ToolchainPrebuiltRoot)\bin\*@id_gcc@.exe) do (
+    @echo CMAKE_@id_lang@_COMPILER=%%i
+    goto :done
+    )
+)
+if "$(ToolchainName)"=="clang" (
+  for %%i in ($(ToolchainPrebuiltRoot)\bin\*@id_clang@.exe) do (
+    @echo CMAKE_@id_lang@_COMPILER=%%i
+    goto :done
+  )
+)
+:done
+</Command>
+    </PostBuildEvent>
+  </ItemDefinitionGroup>
+  <ItemGroup>
+    <ClCompile Include="@id_src@" />
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+</Project>
diff --git a/Modules/CompilerId/Xcode-3.pbxproj.in b/Modules/CompilerId/Xcode-3.pbxproj.in
index eabfc6b..aebae27 100644
--- a/Modules/CompilerId/Xcode-3.pbxproj.in
+++ b/Modules/CompilerId/Xcode-3.pbxproj.in
@@ -29,7 +29,7 @@
 			);
 			name = CompilerId@id_lang@;
 			productName = CompilerId@id_lang@;
-			productType = "com.apple.product-type.tool";
+			productType = "@id_product_type@";
 		};
 		08FB7793FE84155DC02AAC07 = {
 			isa = PBXProject;
@@ -81,6 +81,7 @@
 			buildSettings = {
 				ARCHS = "$(ARCHS_STANDARD_32_BIT)";
 				ONLY_ACTIVE_ARCH = YES;
+				@id_code_sign_identity@
 				CONFIGURATION_BUILD_DIR = "$(BUILD_DIR)";
 				SYMROOT = .;
 				@id_toolset@
diff --git a/Modules/DartConfiguration.tcl.in b/Modules/DartConfiguration.tcl.in
index 68fadf6..37a0a40 100644
--- a/Modules/DartConfiguration.tcl.in
+++ b/Modules/DartConfiguration.tcl.in
@@ -37,6 +37,9 @@
 MakeCommand: @MAKECOMMAND@
 DefaultCTestConfigurationType: @DEFAULT_CTEST_CONFIGURATION_TYPE@
 
+# version control
+UpdateVersionOnly: @CTEST_UPDATE_VERSION_ONLY@
+
 # CVS options
 # Default is "-d -P -A"
 CVSCommand: @CVSCOMMAND@
@@ -71,6 +74,8 @@
 PurifyCommand: @PURIFYCOMMAND@
 ValgrindCommand: @VALGRIND_COMMAND@
 ValgrindCommandOptions: @VALGRIND_COMMAND_OPTIONS@
+MemoryCheckType: @MEMORYCHECK_TYPE@
+MemoryCheckSanitizerOptions: @MEMORYCHECK_SANITIZER_OPTIONS@
 MemoryCheckCommand: @MEMORYCHECK_COMMAND@
 MemoryCheckCommandOptions: @MEMORYCHECK_COMMAND_OPTIONS@
 MemoryCheckSuppressionFile: @MEMORYCHECK_SUPPRESSIONS_FILE@
diff --git a/Modules/DeployQt4.cmake b/Modules/DeployQt4.cmake
index 9b31567..b1a2370 100644
--- a/Modules/DeployQt4.cmake
+++ b/Modules/DeployQt4.cmake
@@ -37,7 +37,8 @@
 #
 # ::
 #
-#   FIXUP_QT4_EXECUTABLE(<executable> [<qtplugins> <libs> <dirs> <plugins_dir> <request_qt_conf>])
+#   FIXUP_QT4_EXECUTABLE(<executable>
+#     [<qtplugins> <libs> <dirs> <plugins_dir> <request_qt_conf>])
 #
 # Copies Qt plugins, writes a Qt configuration file (if needed) and
 # fixes up a Qt4 executable using BundleUtilities so it is standalone
@@ -63,7 +64,8 @@
 #
 # ::
 #
-#   INSTALL_QT4_PLUGIN_PATH(plugin executable copy installed_plugin_path_var <plugins_dir> <component> <configurations>)
+#   INSTALL_QT4_PLUGIN_PATH(plugin executable copy installed_plugin_path_var
+#                           <plugins_dir> <component> <configurations>)
 #
 # Install (or copy) a resolved <plugin> to the default plugins directory
 # (or <plugins_dir>) relative to <executable> and store the result in
@@ -77,7 +79,8 @@
 #
 # ::
 #
-#   INSTALL_QT4_PLUGIN(plugin executable copy installed_plugin_path_var <plugins_dir> <component>)
+#   INSTALL_QT4_PLUGIN(plugin executable copy installed_plugin_path_var
+#                      <plugins_dir> <component>)
 #
 # Install (or copy) an unresolved <plugin> to the default plugins
 # directory (or <plugins_dir>) relative to <executable> and store the
@@ -86,7 +89,8 @@
 #
 # ::
 #
-#   INSTALL_QT4_EXECUTABLE(<executable> [<qtplugins> <libs> <dirs> <plugins_dir> <request_qt_conf> <component>])
+#   INSTALL_QT4_EXECUTABLE(<executable>
+#     [<qtplugins> <libs> <dirs> <plugins_dir> <request_qt_conf> <component>])
 #
 # Installs Qt plugins, writes a Qt configuration file (if needed) and
 # fixes up a Qt4 executable using BundleUtilities so it is standalone
diff --git a/Modules/ExternalData.cmake b/Modules/ExternalData.cmake
index 73a4990..79bb064 100644
--- a/Modules/ExternalData.cmake
+++ b/Modules/ExternalData.cmake
@@ -76,7 +76,7 @@
 #  SHA512      .sha512   US Secure Hash Algorithms, RFC 4634
 #
 # Note that the hashes are used only for unique data identification and
-# download verification.  This is not security software.
+# download verification.
 #
 # Example usage:
 #
diff --git a/Modules/ExternalProject.cmake b/Modules/ExternalProject.cmake
index 0d35cca..d6a6b72 100644
--- a/Modules/ExternalProject.cmake
+++ b/Modules/ExternalProject.cmake
@@ -26,7 +26,7 @@
 #    [CVS_MODULE mod]            # Module to checkout from CVS repo
 #    [CVS_TAG tag]               # Tag to checkout from CVS repo
 #    [SVN_REPOSITORY url]        # URL of Subversion repo
-#    [SVN_REVISION rev]          # Revision to checkout from Subversion repo
+#    [SVN_REVISION -r<rev>]      # Revision to checkout from Subversion repo
 #    [SVN_USERNAME john ]        # Username for Subversion checkout and update
 #    [SVN_PASSWORD doe ]         # Password for Subversion checkout and update
 #    [SVN_TRUST_CERT 1 ]         # Trust the Subversion server site certificate
@@ -49,6 +49,7 @@
 #    [CONFIGURE_COMMAND cmd...]  # Build tree configuration command
 #    [CMAKE_COMMAND /.../cmake]  # Specify alternative cmake executable
 #    [CMAKE_GENERATOR gen]       # Specify generator for native build
+#    [CMAKE_GENERATOR_PLATFORM p] # Generator-specific platform name
 #    [CMAKE_GENERATOR_TOOLSET t] # Generator-specific toolset name
 #    [CMAKE_ARGS args...]        # Arguments to CMake command line
 #    [CMAKE_CACHE_ARGS args...]  # Initial cache arguments, of the form -Dvar:string=on
@@ -239,7 +240,7 @@
     set(is_value 1)
 
     if(arg MATCHES "^[A-Z][A-Z0-9_][A-Z0-9_]+$" AND
-        NOT ((arg STREQUAL "${key}") AND (key STREQUAL "COMMAND")) AND
+        NOT (("x${arg}x" STREQUAL "x${key}x") AND ("x${key}x" STREQUAL "xCOMMANDx")) AND
         NOT arg MATCHES "^(TRUE|FALSE)$")
       if(_ep_keywords_${f} AND arg MATCHES "${_ep_keywords_${f}}")
         set(is_value 0)
@@ -627,11 +628,6 @@
     set(show_progress "SHOW_PROGRESS")
   endif()
 
-  if("${hash}" MATCHES "${_ep_hash_regex}")
-    set(hash_args EXPECTED_HASH ${CMAKE_MATCH_1}=${CMAKE_MATCH_2})
-  else()
-    set(hash_args "# no EXPECTED_HASH")
-  endif()
   # check for curl globals in the project
   if(DEFINED CMAKE_TLS_VERIFY)
     set(tls_verify "set(CMAKE_TLS_VERIFY ${CMAKE_TLS_VERIFY})")
@@ -667,7 +663,6 @@
   \"${remote}\"
   \"${local}\"
   ${show_progress}
-  ${hash_args}
   ${timeout_args}
   STATUS status
   LOG log)
@@ -711,6 +706,7 @@
     file(REMOVE \"\${file}\")
     execute_process(COMMAND \${CMAKE_COMMAND} -P \"${download_script}\")
   endif()
+  math(EXPR attempt \"\${attempt} + 1\")
 endwhile()
 
 if(\${succeeded})
@@ -737,7 +733,7 @@
 function(_ep_write_extractfile_script script_filename name filename directory)
   set(args "")
 
-  if(filename MATCHES "(\\.|=)(bz2|tar\\.gz|tgz|zip)$")
+  if(filename MATCHES "(\\.|=)(7z|tar\\.bz2|tar\\.gz|tar\\.xz|tbz2|tgz|txz|zip)$")
     set(args xfz)
   endif()
 
@@ -746,7 +742,7 @@
   endif()
 
   if(args STREQUAL "")
-    message(SEND_ERROR "error: do not know how to extract '${filename}' -- known types are .bz2, .tar, .tar.gz, .tgz and .zip")
+    message(SEND_ERROR "error: do not know how to extract '${filename}' -- known types are .7z, .tar, .tar.bz2, .tar.gz, .tar.xz, .tbz2, .tgz, .txz and .zip")
     return()
   endif()
 
@@ -1540,11 +1536,11 @@
         if("x${fname}" STREQUAL "x")
           string(REGEX MATCH "[^/\\?]*$" fname "${url}")
         endif()
-        if(NOT "${fname}" MATCHES "(\\.|=)(bz2|tar|tgz|tar\\.gz|zip)$")
-          string(REGEX MATCH "([^/\\?]+(\\.|=)(bz2|tar|tgz|tar\\.gz|zip))/.*$" match_result "${url}")
+        if(NOT "${fname}" MATCHES "(\\.|=)(7z|tar|tar\\.bz2|tar\\.gz|tar\\.xz|tbz2|tgz|txz|zip)$")
+          string(REGEX MATCH "([^/\\?]+(\\.|=)(7z|tar|tar\\.bz2|tar\\.gz|tar\\.xz|tbz2|tgz|txz|zip))/.*$" match_result "${url}")
           set(fname "${CMAKE_MATCH_1}")
         endif()
-        if(NOT "${fname}" MATCHES "(\\.|=)(bz2|tar|tgz|tar\\.gz|zip)$")
+        if(NOT "${fname}" MATCHES "(\\.|=)(7z|tar|tar\\.bz2|tar\\.gz|tar\\.xz|tbz2|tgz|txz|zip)$")
           message(FATAL_ERROR "Could not extract tarball filename from url:\n  ${url}")
         endif()
         string(REPLACE ";" "-" fname "${fname}")
@@ -1757,9 +1753,13 @@
     endif()
 
     get_target_property(cmake_generator ${name} _EP_CMAKE_GENERATOR)
+    get_target_property(cmake_generator_platform ${name} _EP_CMAKE_GENERATOR_PLATFORM)
     get_target_property(cmake_generator_toolset ${name} _EP_CMAKE_GENERATOR_TOOLSET)
     if(cmake_generator)
       list(APPEND cmd "-G${cmake_generator}")
+      if(cmake_generator_platform)
+        list(APPEND cmd "-A${cmake_generator_platform}")
+      endif()
       if(cmake_generator_toolset)
         list(APPEND cmd "-T${cmake_generator_toolset}")
       endif()
@@ -1769,6 +1769,12 @@
       else()
         list(APPEND cmd "-G${CMAKE_GENERATOR}")
       endif()
+      if(cmake_generator_platform)
+        message(FATAL_ERROR "Option CMAKE_GENERATOR_PLATFORM not allowed without CMAKE_GENERATOR.")
+      endif()
+      if(CMAKE_GENERATOR_PLATFORM)
+        list(APPEND cmd "-A${CMAKE_GENERATOR_PLATFORM}")
+      endif()
       if(cmake_generator_toolset)
         message(FATAL_ERROR "Option CMAKE_GENERATOR_TOOLSET not allowed without CMAKE_GENERATOR.")
       endif()
diff --git a/Modules/FeatureSummary.cmake b/Modules/FeatureSummary.cmake
index 12ea384..37bc6b5 100644
--- a/Modules/FeatureSummary.cmake
+++ b/Modules/FeatureSummary.cmake
@@ -55,21 +55,32 @@
 # The WHAT option is the only mandatory option.  Here you specify what
 # information will be printed:
 #
-# ::
-#
-#     ALL: print everything
-#     ENABLED_FEATURES: the list of all features which are enabled
-#     DISABLED_FEATURES: the list of all features which are disabled
-#     PACKAGES_FOUND: the list of all packages which have been found
-#     PACKAGES_NOT_FOUND: the list of all packages which have not been found
-#     OPTIONAL_PACKAGES_FOUND: only those packages which have been found which have the type OPTIONAL
-#     OPTIONAL_PACKAGES_NOT_FOUND: only those packages which have not been found which have the type OPTIONAL
-#     RECOMMENDED_PACKAGES_FOUND: only those packages which have been found which have the type RECOMMENDED
-#     RECOMMENDED_PACKAGES_NOT_FOUND: only those packages which have not been found which have the type RECOMMENDED
-#     REQUIRED_PACKAGES_FOUND: only those packages which have been found which have the type REQUIRED
-#     REQUIRED_PACKAGES_NOT_FOUND: only those packages which have not been found which have the type REQUIRED
-#     RUNTIME_PACKAGES_FOUND: only those packages which have been found which have the type RUNTIME
-#     RUNTIME_PACKAGES_NOT_FOUND: only those packages which have not been found which have the type RUNTIME
+# ``ALL``
+#  print everything
+# ``ENABLED_FEATURES``
+#  the list of all features which are enabled
+# ``DISABLED_FEATURES``
+#  the list of all features which are disabled
+# ``PACKAGES_FOUND``
+#  the list of all packages which have been found
+# ``PACKAGES_NOT_FOUND``
+#  the list of all packages which have not been found
+# ``OPTIONAL_PACKAGES_FOUND``
+#  only those packages which have been found which have the type OPTIONAL
+# ``OPTIONAL_PACKAGES_NOT_FOUND``
+#  only those packages which have not been found which have the type OPTIONAL
+# ``RECOMMENDED_PACKAGES_FOUND``
+#  only those packages which have been found which have the type RECOMMENDED
+# ``RECOMMENDED_PACKAGES_NOT_FOUND``
+#  only those packages which have not been found which have the type RECOMMENDED
+# ``REQUIRED_PACKAGES_FOUND``
+#  only those packages which have been found which have the type REQUIRED
+# ``REQUIRED_PACKAGES_NOT_FOUND``
+#  only those packages which have not been found which have the type REQUIRED
+# ``RUNTIME_PACKAGES_FOUND``
+#  only those packages which have been found which have the type RUNTIME
+# ``RUNTIME_PACKAGES_NOT_FOUND``
+#  only those packages which have not been found which have the type RUNTIME
 #
 # With the exception of the ``ALL`` value, these values can be combined
 # in order to customize the output. For example:
@@ -118,10 +129,11 @@
 #
 # ::
 #
-#     SET_PACKAGE_PROPERTIES(<name> PROPERTIES [ URL <url> ]
-#                                              [ DESCRIPTION <description> ]
-#                                              [ TYPE (RUNTIME|OPTIONAL|RECOMMENDED|REQUIRED) ]
-#                                              [ PURPOSE <purpose> ]
+#     SET_PACKAGE_PROPERTIES(<name> PROPERTIES
+#                            [ URL <url> ]
+#                            [ DESCRIPTION <description> ]
+#                            [ TYPE (RUNTIME|OPTIONAL|RECOMMENDED|REQUIRED) ]
+#                            [ PURPOSE <purpose> ]
 #                           )
 #
 #
@@ -171,26 +183,30 @@
 # ::
 #
 #    find_package(LibXml2)
-#    set_package_properties(LibXml2 PROPERTIES DESCRIPTION "A XML processing library."
-#                                              URL "http://xmlsoft.org/")
+#    set_package_properties(LibXml2 PROPERTIES
+#                           DESCRIPTION "A XML processing library."
+#                           URL "http://xmlsoft.org/")
 #
 #
 #
 # ::
 #
-#    set_package_properties(LibXml2 PROPERTIES TYPE RECOMMENDED
-#                                              PURPOSE "Enables HTML-import in MyWordProcessor")
+#    set_package_properties(LibXml2 PROPERTIES
+#                           TYPE RECOMMENDED
+#                           PURPOSE "Enables HTML-import in MyWordProcessor")
 #    ...
-#    set_package_properties(LibXml2 PROPERTIES TYPE OPTIONAL
-#                                              PURPOSE "Enables odt-export in MyWordProcessor")
+#    set_package_properties(LibXml2 PROPERTIES
+#                           TYPE OPTIONAL
+#                           PURPOSE "Enables odt-export in MyWordProcessor")
 #
 #
 #
 # ::
 #
 #    find_package(DBUS)
-#    set_package_properties(DBUS PROPERTIES TYPE RUNTIME
-#                                              PURPOSE "Necessary to disable the screensaver during a presentation" )
+#    set_package_properties(DBUS PROPERTIES
+#      TYPE RUNTIME
+#      PURPOSE "Necessary to disable the screensaver during a presentation" )
 #
 #
 #
diff --git a/Modules/FindBacktrace.cmake b/Modules/FindBacktrace.cmake
index 5620661..cb4f60a 100644
--- a/Modules/FindBacktrace.cmake
+++ b/Modules/FindBacktrace.cmake
@@ -5,18 +5,24 @@
 # Find provider for backtrace(3).
 #
 # Checks if OS supports backtrace(3) via either libc or custom library.
-# This module defines the following variables::
+# This module defines the following variables:
 #
-#  Backtrace_HEADER       - The header file needed for backtrace(3). Cached.
-#                           Could be forcibly set by user.
-#  Backtrace_INCLUDE_DIRS - The include directories needed to use backtrace(3) header.
-#  Backtrace_LIBRARIES    - The libraries (linker flags) needed to use backtrace(3), if any.
-#  Backtrace_FOUND        - Is set if and only if backtrace(3) support detected.
+# ``Backtrace_HEADER``
+#   The header file needed for backtrace(3). Cached.
+#   Could be forcibly set by user.
+# ``Backtrace_INCLUDE_DIRS``
+#   The include directories needed to use backtrace(3) header.
+# ``Backtrace_LIBRARIES``
+#   The libraries (linker flags) needed to use backtrace(3), if any.
+# ``Backtrace_FOUND``
+#   Is set if and only if backtrace(3) support detected.
 #
-# The following cache variables are also available to set or use::
+# The following cache variables are also available to set or use:
 #
-#  Backtrace_LIBRARY     - The external library providing backtrace, if any.
-#  Backtrace_INCLUDE_DIR - The directory holding the backtrace(3) header.
+# ``Backtrace_LIBRARY``
+#   The external library providing backtrace, if any.
+# ``Backtrace_INCLUDE_DIR``
+#   The directory holding the backtrace(3) header.
 #
 # Typical usage is to generate of header file using configure_file() with the
 # contents like the following::
@@ -44,7 +50,7 @@
 
 include(CMakePushCheckState)
 include(CheckSymbolExists)
-include(FindPackageHandleStandardArgs)
+include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 
 # List of variables to be provided to find_package_handle_standard_args()
 set(_Backtrace_STD_ARGS Backtrace_INCLUDE_DIR)
diff --git a/Modules/FindBoost.cmake b/Modules/FindBoost.cmake
index dfd4460..3642b3e 100644
--- a/Modules/FindBoost.cmake
+++ b/Modules/FindBoost.cmake
@@ -375,14 +375,16 @@
 # Guesses Boost's compiler prefix used in built library names
 # Returns the guess by setting the variable pointed to by _ret
 function(_Boost_GUESS_COMPILER_PREFIX _ret)
-  if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Intel"
-      OR "${CMAKE_CXX_COMPILER}" MATCHES "icl"
-      OR "${CMAKE_CXX_COMPILER}" MATCHES "icpc")
+  if(CMAKE_CXX_COMPILER_ID STREQUAL "Intel"
+      OR CMAKE_CXX_COMPILER MATCHES "icl"
+      OR CMAKE_CXX_COMPILER MATCHES "icpc")
     if(WIN32)
       set (_boost_COMPILER "-iw")
     else()
       set (_boost_COMPILER "-il")
     endif()
+  elseif (MSVC14)
+    set(_boost_COMPILER "-vc140")
   elseif (MSVC12)
     set(_boost_COMPILER "-vc120")
   elseif (MSVC11)
@@ -401,7 +403,7 @@
     set(_boost_COMPILER "-vc6") # yes, this is correct
   elseif (BORLAND)
     set(_boost_COMPILER "-bcb")
-  elseif("${CMAKE_CXX_COMPILER_ID}" STREQUAL "SunPro")
+  elseif(CMAKE_CXX_COMPILER_ID STREQUAL "SunPro")
     set(_boost_COMPILER "-sw")
   elseif (MINGW)
     if(${Boost_MAJOR_VERSION}.${Boost_MINOR_VERSION} VERSION_LESS 1.34)
diff --git a/Modules/FindCUDA.cmake b/Modules/FindCUDA.cmake
index d9809ad..3dd975c 100644
--- a/Modules/FindCUDA.cmake
+++ b/Modules/FindCUDA.cmake
@@ -452,7 +452,17 @@
 if(CMAKE_GENERATOR MATCHES "Visual Studio")
   set(CUDA_HOST_COMPILER "$(VCInstallDir)bin" CACHE FILEPATH "Host side compiler used by NVCC")
 else()
-  set(CUDA_HOST_COMPILER "${CMAKE_C_COMPILER}" CACHE FILEPATH "Host side compiler used by NVCC")
+  # Using cc which is symlink to clang may let NVCC think it is GCC and issue
+  # unhandled -dumpspecs option to clang. Also in case neither
+  # CMAKE_C_COMPILER is defined (project does not use C language) nor
+  # CUDA_HOST_COMPILER is specified manually we should skip -ccbin and let
+  # nvcc use its own default C compiler.
+  if(DEFINED CMAKE_C_COMPILER AND NOT DEFINED CUDA_HOST_COMPILER)
+    get_filename_component(c_compiler_realpath "${CMAKE_C_COMPILER}" REALPATH)
+  else()
+    set(c_compiler_realpath "")
+  endif()
+  set(CUDA_HOST_COMPILER "${c_compiler_realpath}" CACHE FILEPATH "Host side compiler used by NVCC")
 endif()
 
 # Propagate the host flags to the host compiler via -Xcompiler
@@ -693,18 +703,6 @@
 else()
   set(CUDA_LIBRARIES ${CUDA_CUDART_LIBRARY})
 endif()
-if(APPLE)
-  # We need to add the path to cudart to the linker using rpath, since the
-  # library name for the cuda libraries is prepended with @rpath.
-  if(CUDA_BUILD_EMULATION AND CUDA_CUDARTEMU_LIBRARY)
-    get_filename_component(_cuda_path_to_cudart "${CUDA_CUDARTEMU_LIBRARY}" PATH)
-  else()
-    get_filename_component(_cuda_path_to_cudart "${CUDA_CUDART_LIBRARY}" PATH)
-  endif()
-  if(_cuda_path_to_cudart)
-    list(APPEND CUDA_LIBRARIES -Wl,-rpath "-Wl,${_cuda_path_to_cudart}")
-  endif()
-endif()
 
 # 1.1 toolkit on linux doesn't appear to have a separate library on
 # some platforms.
@@ -884,15 +882,15 @@
   set( ${_options} )
   set( _found_options FALSE )
   foreach(arg ${ARGN})
-    if(arg STREQUAL "OPTIONS")
+    if("x${arg}" STREQUAL "xOPTIONS")
       set( _found_options TRUE )
     elseif(
-        arg STREQUAL "WIN32" OR
-        arg STREQUAL "MACOSX_BUNDLE" OR
-        arg STREQUAL "EXCLUDE_FROM_ALL" OR
-        arg STREQUAL "STATIC" OR
-        arg STREQUAL "SHARED" OR
-        arg STREQUAL "MODULE"
+        "x${arg}" STREQUAL "xWIN32" OR
+        "x${arg}" STREQUAL "xMACOSX_BUNDLE" OR
+        "x${arg}" STREQUAL "xEXCLUDE_FROM_ALL" OR
+        "x${arg}" STREQUAL "xSTATIC" OR
+        "x${arg}" STREQUAL "xSHARED" OR
+        "x${arg}" STREQUAL "xMODULE"
         )
       list(APPEND ${_cmake_options} ${arg})
     else()
@@ -1422,7 +1420,7 @@
     # If -ccbin, --compiler-bindir has been specified, don't do anything.  Otherwise add it here.
     list( FIND nvcc_flags "-ccbin" ccbin_found0 )
     list( FIND nvcc_flags "--compiler-bindir" ccbin_found1 )
-    if( ccbin_found0 LESS 0 AND ccbin_found1 LESS 0 )
+    if( ccbin_found0 LESS 0 AND ccbin_found1 LESS 0 AND CUDA_HOST_COMPILER )
       list(APPEND nvcc_flags -ccbin "\"${CUDA_HOST_COMPILER}\"")
     endif()
     # Create a list of flags specified by CUDA_NVCC_FLAGS_${CONFIG}
diff --git a/Modules/FindCUDA/run_nvcc.cmake b/Modules/FindCUDA/run_nvcc.cmake
index f0aac84..abdd307 100644
--- a/Modules/FindCUDA/run_nvcc.cmake
+++ b/Modules/FindCUDA/run_nvcc.cmake
@@ -62,7 +62,7 @@
 set(CUDA_make2cmake "@CUDA_make2cmake@") # path
 set(CUDA_parse_cubin "@CUDA_parse_cubin@") # path
 set(build_cubin @build_cubin@) # bool
-set(CUDA_HOST_COMPILER "@CUDA_HOST_COMPILER@") # bool
+set(CUDA_HOST_COMPILER "@CUDA_HOST_COMPILER@") # path
 # We won't actually use these variables for now, but we need to set this, in
 # order to force this file to be run again if it changes.
 set(generated_file_path "@generated_file_path@") # path
@@ -106,7 +106,7 @@
 # Any -ccbin existing in CUDA_NVCC_FLAGS gets highest priority
 list( FIND CUDA_NVCC_FLAGS "-ccbin" ccbin_found0 )
 list( FIND CUDA_NVCC_FLAGS "--compiler-bindir" ccbin_found1 )
-if( ccbin_found0 LESS 0 AND ccbin_found1 LESS 0 )
+if( ccbin_found0 LESS 0 AND ccbin_found1 LESS 0 AND CUDA_HOST_COMPILER )
   if (CUDA_HOST_COMPILER STREQUAL "$(VCInstallDir)bin" AND DEFINED CCBIN)
     set(CCBIN -ccbin "${CCBIN}")
   else()
@@ -126,7 +126,7 @@
 # and other return variables are present after executing the process.
 macro(cuda_execute_process status command)
   set(_command ${command})
-  if(NOT _command STREQUAL "COMMAND")
+  if(NOT "x${_command}" STREQUAL "xCOMMAND")
     message(FATAL_ERROR "Malformed call to cuda_execute_process.  Missing COMMAND as second argument. (command = ${command})")
   endif()
   if(verbose)
diff --git a/Modules/FindCurses.cmake b/Modules/FindCurses.cmake
index 9b633c7..0184c39 100644
--- a/Modules/FindCurses.cmake
+++ b/Modules/FindCurses.cmake
@@ -2,28 +2,43 @@
 # FindCurses
 # ----------
 #
-# Find the curses include file and library
+# Find the curses or ncurses include file and library.
 #
+# Result Variables
+# ^^^^^^^^^^^^^^^^
 #
+# This module defines the following variables:
 #
-# ::
+# ``CURSES_FOUND``
+#   True if Curses is found.
+# ``CURSES_INCLUDE_DIRS``
+#   The include directories needed to use Curses.
+# ``CURSES_LIBRARIES``
+#   The libraries needed to use Curses.
+# ``CURSES_HAVE_CURSES_H``
+#   True if curses.h is available.
+# ``CURSES_HAVE_NCURSES_H``
+#   True if ncurses.h is available.
+# ``CURSES_HAVE_NCURSES_NCURSES_H``
+#   True if ``ncurses/ncurses.h`` is available.
+# ``CURSES_HAVE_NCURSES_CURSES_H``
+#   True if ``ncurses/curses.h`` is available.
 #
-#   CURSES_FOUND - system has Curses
-#   CURSES_INCLUDE_DIR - the Curses include directory
-#   CURSES_LIBRARIES - The libraries needed to use Curses
-#   CURSES_HAVE_CURSES_H - true if curses.h is available
-#   CURSES_HAVE_NCURSES_H - true if ncurses.h is available
-#   CURSES_HAVE_NCURSES_NCURSES_H - true if ncurses/ncurses.h is available
-#   CURSES_HAVE_NCURSES_CURSES_H - true if ncurses/curses.h is available
-#   CURSES_LIBRARY - set for backwards compatibility with 2.4 CMake
+# Set ``CURSES_NEED_NCURSES`` to ``TRUE`` before the
+# ``find_package(Curses)`` call if NCurses functionality is required.
 #
+# Backward Compatibility
+# ^^^^^^^^^^^^^^^^^^^^^^
 #
+# The following variable are provided for backward compatibility:
 #
-# Set CURSES_NEED_NCURSES to TRUE before the find_package() command if
-# NCurses functionality is required.
+# ``CURSES_INCLUDE_DIR``
+#   Path to Curses include.  Use ``CURSES_INCLUDE_DIRS`` instead.
+# ``CURSES_LIBRARY``
+#   Path to Curses library.  Use ``CURSES_LIBRARIES`` instead.
 
 #=============================================================================
-# Copyright 2001-2009 Kitware, Inc.
+# Copyright 2001-2014 Kitware, Inc.
 #
 # Distributed under the OSI-approved BSD License (the "License");
 # see accompanying file Copyright.txt for details.
@@ -84,59 +99,27 @@
 
 endif()
 
-
-if(NOT CURSES_USE_NCURSES)
-  find_file(CURSES_HAVE_CURSES_H curses.h )
-  find_path(CURSES_CURSES_H_PATH curses.h )
-  get_filename_component(_cursesLibDir "${CURSES_CURSES_LIBRARY}" PATH)
-  get_filename_component(_cursesParentDir "${_cursesLibDir}" PATH)
-
-  # for compatibility with older FindCurses.cmake this has to be in the cache
-  # FORCE must not be used since this would break builds which preload a cache wqith these variables set
-  set(CURSES_INCLUDE_PATH "${CURSES_CURSES_H_PATH}"
-    CACHE FILEPATH "The curses include path")
-  set(CURSES_LIBRARY "${CURSES_CURSES_LIBRARY}"
-    CACHE FILEPATH "The curses library")
-else()
-# we need to find ncurses
+if(CURSES_USE_NCURSES)
   get_filename_component(_cursesLibDir "${CURSES_NCURSES_LIBRARY}" PATH)
   get_filename_component(_cursesParentDir "${_cursesLibDir}" PATH)
 
-  find_file(CURSES_HAVE_NCURSES_H         ncurses.h)
-  find_file(CURSES_HAVE_NCURSES_NCURSES_H ncurses/ncurses.h)
-  find_file(CURSES_HAVE_NCURSES_CURSES_H  ncurses/curses.h)
-  find_file(CURSES_HAVE_CURSES_H          curses.h
-    HINTS "${_cursesParentDir}/include")
-
-  find_path(CURSES_NCURSES_INCLUDE_PATH ncurses.h ncurses/ncurses.h
-    ncurses/curses.h)
-  find_path(CURSES_NCURSES_INCLUDE_PATH curses.h
-    HINTS "${_cursesParentDir}/include")
-
-  # for compatibility with older FindCurses.cmake this has to be in the cache
-  # FORCE must not be used since this would break builds which preload
-  # however if the value of the variable has NOTFOUND in it, then
-  # it is OK to force, and we need to force in order to have it work.
-  # a cache wqith these variables set
-  # only put ncurses include and library into
-  # variables if they are found
-  if(NOT CURSES_NCURSES_INCLUDE_PATH AND CURSES_HAVE_NCURSES_NCURSES_H)
-    get_filename_component(CURSES_NCURSES_INCLUDE_PATH
-      "${CURSES_HAVE_NCURSES_NCURSES_H}" PATH)
+  # Use CURSES_NCURSES_INCLUDE_PATH if set, for compatibility.
+  if(CURSES_NCURSES_INCLUDE_PATH)
+    find_path(CURSES_INCLUDE_PATH
+      NAMES ncurses/ncurses.h ncurses/curses.h ncurses.h curses.h
+      PATHS ${CURSES_NCURSES_INCLUDE_PATH}
+      NO_DEFAULT_PATH
+      )
   endif()
-  if(CURSES_NCURSES_INCLUDE_PATH AND CURSES_NCURSES_LIBRARY)
-    set( FORCE_IT )
-    if(CURSES_INCLUDE_PATH MATCHES NOTFOUND)
-      set(FORCE_IT FORCE)
-    endif()
-    set(CURSES_INCLUDE_PATH "${CURSES_NCURSES_INCLUDE_PATH}"
-      CACHE FILEPATH "The curses include path" ${FORCE_IT})
-    set( FORCE_IT)
-    if(CURSES_LIBRARY MATCHES NOTFOUND)
-      set(FORCE_IT FORCE)
-    endif()
-    set(CURSES_LIBRARY "${CURSES_NCURSES_LIBRARY}"
-      CACHE FILEPATH "The curses library" ${FORCE_IT})
+
+  find_path(CURSES_INCLUDE_PATH
+    NAMES ncurses/ncurses.h ncurses/curses.h ncurses.h curses.h
+    HINTS "${_cursesParentDir}/include"
+    )
+
+  # Previous versions of FindCurses provided these values.
+  if(NOT DEFINED CURSES_LIBRARY)
+    set(CURSES_LIBRARY "${CURSES_NCURSES_LIBRARY}")
   endif()
 
   CHECK_LIBRARY_EXISTS("${CURSES_NCURSES_LIBRARY}"
@@ -147,6 +130,52 @@
     CHECK_LIBRARY_EXISTS("${CURSES_EXTRA_LIBRARY}"
       cbreak "" CURSES_TINFO_HAS_CBREAK)
   endif()
+else()
+  get_filename_component(_cursesLibDir "${CURSES_CURSES_LIBRARY}" PATH)
+  get_filename_component(_cursesParentDir "${_cursesLibDir}" PATH)
+
+  find_path(CURSES_INCLUDE_PATH
+    NAMES curses.h
+    HINTS "${_cursesParentDir}/include"
+    )
+
+  # Previous versions of FindCurses provided these values.
+  if(NOT DEFINED CURSES_CURSES_H_PATH)
+    set(CURSES_CURSES_H_PATH "${CURSES_INCLUDE_PATH}")
+  endif()
+  if(NOT DEFINED CURSES_LIBRARY)
+    set(CURSES_LIBRARY "${CURSES_CURSES_LIBRARY}")
+  endif()
+endif()
+
+# Report whether each possible header name exists in the include directory.
+if(NOT DEFINED CURSES_HAVE_NCURSES_NCURSES_H)
+  if(EXISTS "${CURSES_INCLUDE_PATH}/ncurses/ncurses.h")
+    set(CURSES_HAVE_NCURSES_NCURSES_H "${CURSES_INCLUDE_PATH}/ncurses/ncurses.h")
+  else()
+    set(CURSES_HAVE_NCURSES_NCURSES_H "CURSES_HAVE_NCURSES_NCURSES_H-NOTFOUND")
+  endif()
+endif()
+if(NOT DEFINED CURSES_HAVE_NCURSES_CURSES_H)
+  if(EXISTS "${CURSES_INCLUDE_PATH}/ncurses/curses.h")
+    set(CURSES_HAVE_NCURSES_CURSES_H "${CURSES_INCLUDE_PATH}/ncurses/curses.h")
+  else()
+    set(CURSES_HAVE_NCURSES_CURSES_H "CURSES_HAVE_NCURSES_CURSES_H-NOTFOUND")
+  endif()
+endif()
+if(NOT DEFINED CURSES_HAVE_NCURSES_H)
+  if(EXISTS "${CURSES_INCLUDE_PATH}/ncurses.h")
+    set(CURSES_HAVE_NCURSES_H "${CURSES_INCLUDE_PATH}/ncurses.h")
+  else()
+    set(CURSES_HAVE_NCURSES_H "CURSES_HAVE_NCURSES_H-NOTFOUND")
+  endif()
+endif()
+if(NOT DEFINED CURSES_HAVE_CURSES_H)
+  if(EXISTS "${CURSES_INCLUDE_PATH}/curses.h")
+    set(CURSES_HAVE_CURSES_H "${CURSES_INCLUDE_PATH}/curses.h")
+  else()
+    set(CURSES_HAVE_CURSES_H "CURSES_HAVE_CURSES_H-NOTFOUND")
+  endif()
 endif()
 
 if (NOT CURSES_TINFO_HAS_CBREAK)
@@ -157,11 +186,10 @@
 find_library(CURSES_FORM_LIBRARY form HINTS "${_cursesLibDir}")
 find_library(CURSES_FORM_LIBRARY form )
 
-# for compatibility with older FindCurses.cmake this has to be in the cache
-# FORCE must not be used since this would break builds which preload a cache
-# qith these variables set
-set(FORM_LIBRARY "${CURSES_FORM_LIBRARY}"
-  CACHE FILEPATH "The curses form library")
+# Previous versions of FindCurses provided these values.
+if(NOT DEFINED FORM_LIBRARY)
+  set(FORM_LIBRARY "${CURSES_FORM_LIBRARY}")
+endif()
 
 # Need to provide the *_LIBRARIES
 set(CURSES_LIBRARIES ${CURSES_LIBRARY})
@@ -174,8 +202,9 @@
   set(CURSES_LIBRARIES ${CURSES_LIBRARIES} ${CURSES_FORM_LIBRARY})
 endif()
 
-# Proper name is *_INCLUDE_DIR
-set(CURSES_INCLUDE_DIR ${CURSES_INCLUDE_PATH})
+# Provide the *_INCLUDE_DIRS result.
+set(CURSES_INCLUDE_DIRS ${CURSES_INCLUDE_PATH})
+set(CURSES_INCLUDE_DIR ${CURSES_INCLUDE_PATH}) # compatibility
 
 # handle the QUIETLY and REQUIRED arguments and set CURSES_FOUND to TRUE if
 # all listed variables are TRUE
@@ -185,18 +214,7 @@
 
 mark_as_advanced(
   CURSES_INCLUDE_PATH
-  CURSES_LIBRARY
-  CURSES_CURSES_INCLUDE_PATH
   CURSES_CURSES_LIBRARY
-  CURSES_NCURSES_INCLUDE_PATH
   CURSES_NCURSES_LIBRARY
   CURSES_EXTRA_LIBRARY
-  FORM_LIBRARY
-  CURSES_LIBRARIES
-  CURSES_INCLUDE_DIR
-  CURSES_CURSES_HAS_WSYNCUP
-  CURSES_NCURSES_HAS_WSYNCUP
-  CURSES_NCURSES_HAS_CBREAK
-  CURSES_TINFO_HAS_CBREAK
   )
-
diff --git a/Modules/FindGLEW.cmake b/Modules/FindGLEW.cmake
index 497a80c..f42182f 100644
--- a/Modules/FindGLEW.cmake
+++ b/Modules/FindGLEW.cmake
@@ -4,6 +4,15 @@
 #
 # Find the OpenGL Extension Wrangler Library (GLEW)
 #
+# IMPORTED Targets
+# ^^^^^^^^^^^^^^^^
+#
+# This module defines the :prop_tgt:`IMPORTED` target ``GLEW::GLEW``,
+# if GLEW has been found.
+#
+# Result Variables
+# ^^^^^^^^^^^^^^^^
+#
 # This module defines the following variables:
 #
 # ::
@@ -35,4 +44,11 @@
 find_package_handle_standard_args(GLEW
                                   REQUIRED_VARS GLEW_INCLUDE_DIR GLEW_LIBRARY)
 
+if(GLEW_FOUND AND NOT TARGET GLEW::GLEW)
+  add_library(GLEW::GLEW UNKNOWN IMPORTED)
+  set_target_properties(GLEW::GLEW PROPERTIES
+    IMPORTED_LOCATION "${GLEW_LIBRARY}"
+    INTERFACE_INCLUDE_DIRECTORIES "${GLEW_INCLUDE_DIRS}")
+endif()
+
 mark_as_advanced(GLEW_INCLUDE_DIR GLEW_LIBRARY)
diff --git a/Modules/FindGLUT.cmake b/Modules/FindGLUT.cmake
index be7c0cd..c9f7597 100644
--- a/Modules/FindGLUT.cmake
+++ b/Modules/FindGLUT.cmake
@@ -2,7 +2,20 @@
 # FindGLUT
 # --------
 #
-# try to find glut library and include files
+# try to find glut library and include files.
+#
+# IMPORTED Targets
+# ^^^^^^^^^^^^^^^^
+#
+# This module defines the :prop_tgt:`IMPORTED` targets:
+#
+# ``GLUT::GLUT``
+#  Defined if the system has GLUT.
+#
+# Result Variables
+# ^^^^^^^^^^^^^^^^
+#
+# This module sets the following variables:
 #
 # ::
 #
@@ -42,13 +55,21 @@
 else ()
 
   if (APPLE)
-    # These values for Apple could probably do with improvement.
-    find_path( GLUT_INCLUDE_DIR glut.h
-      /System/Library/Frameworks/GLUT.framework/Versions/A/Headers
-      ${OPENGL_LIBRARY_DIR}
-      )
-    set(GLUT_glut_LIBRARY "-framework GLUT" CACHE STRING "GLUT library for OSX")
-    set(GLUT_cocoa_LIBRARY "-framework Cocoa" CACHE STRING "Cocoa framework for OSX")
+    find_path(GLUT_INCLUDE_DIR glut.h ${OPENGL_LIBRARY_DIR})
+    find_library(GLUT_glut_LIBRARY GLUT DOC "GLUT library for OSX")
+    find_library(GLUT_cocoa_LIBRARY Cocoa DOC "Cocoa framework for OSX")
+
+    if(GLUT_cocoa_LIBRARY AND NOT TARGET GLUT::Cocoa)
+      add_library(GLUT::Cocoa UNKNOWN IMPORTED)
+      # Cocoa should always be a Framework, but we check to make sure.
+      if(GLUT_cocoa_LIBRARY MATCHES "/([^/]+)\\.framework$")
+        set_target_properties(GLUT::Cocoa PROPERTIES
+          IMPORTED_LOCATION "${GLUT_cocoa_LIBRARY}/${CMAKE_MATCH_1}")
+      else()
+        set_target_properties(GLUT::Cocoa PROPERTIES
+          IMPORTED_LOCATION "${GLUT_cocoa_LIBRARY}")
+      endif()
+    endif()
   else ()
 
     if (BEOS)
@@ -66,6 +87,18 @@
         /usr/openwin/lib
         )
 
+      if(GLUT_Xi_LIBRARY AND NOT TARGET GLUT::Xi)
+        add_library(GLUT::Xi UNKNOWN IMPORTED)
+        set_target_properties(GLUT::Xi PROPERTIES
+          IMPORTED_LOCATION "${GLUT_Xi_LIBRARY}")
+      endif()
+
+      if(GLUT_Xmu_LIBRARY AND NOT TARGET GLUT::Xmu)
+        add_library(GLUT::Xmu UNKNOWN IMPORTED)
+        set_target_properties(GLUT::Xmu PROPERTIES
+          IMPORTED_LOCATION "${GLUT_Xmu_LIBRARY}")
+      endif()
+
     endif ()
 
     find_path( GLUT_INCLUDE_DIR GL/glut.h
@@ -102,6 +135,34 @@
     ${GLUT_cocoa_LIBRARY}
     )
 
+  if(NOT TARGET GLUT::GLUT)
+    add_library(GLUT::GLUT UNKNOWN IMPORTED)
+    set_target_properties(GLUT::GLUT PROPERTIES
+      INTERFACE_INCLUDE_DIRECTORIES "${GLUT_INCLUDE_DIR}")
+    if(GLUT_glut_LIBRARY MATCHES "/([^/]+)\\.framework$")
+      set_target_properties(GLUT::GLUT PROPERTIES
+        IMPORTED_LOCATION "${GLUT_glut_LIBRARY}/${CMAKE_MATCH_1}")
+    else()
+      set_target_properties(GLUT::GLUT PROPERTIES
+        IMPORTED_LOCATION "${GLUT_glut_LIBRARY}")
+    endif()
+
+    if(TARGET GLUT::Xmu)
+      set_property(TARGET GLUT::GLUT APPEND
+        PROPERTY INTERFACE_LINK_LIBRARIES GLUT::Xmu)
+    endif()
+
+    if(TARGET GLUT::Xi)
+      set_property(TARGET GLUT::GLUT APPEND
+        PROPERTY INTERFACE_LINK_LIBRARIES GLUT::Xi)
+    endif()
+
+    if(TARGET GLUT::Cocoa)
+      set_property(TARGET GLUT::GLUT APPEND
+        PROPERTY INTERFACE_LINK_LIBRARIES GLUT::Cocoa)
+    endif()
+  endif()
+
   #The following deprecated settings are for backwards compatibility with CMake1.4
   set (GLUT_LIBRARY ${GLUT_LIBRARIES})
   set (GLUT_INCLUDE_PATH ${GLUT_INCLUDE_DIR})
diff --git a/Modules/FindGTK2.cmake b/Modules/FindGTK2.cmake
index eaa5e55..72bb8eb 100644
--- a/Modules/FindGTK2.cmake
+++ b/Modules/FindGTK2.cmake
@@ -527,7 +527,7 @@
             set_property(TARGET GTK2::${_basename} APPEND PROPERTY INTERFACE_INCLUDE_DIRECTORIES "${GTK2_${_var}_INCLUDE_DIR}")
         endif()
 
-        if(GTK2_${_var}CONFIG_INCLUDE_DIR AND NOT "${GTK2_${_var}CONFIG_INCLUDE_DIR}" STREQUAL "GTK2_${_var}_INCLUDE_DIR")
+        if(GTK2_${_var}CONFIG_INCLUDE_DIR AND NOT "x${GTK2_${_var}CONFIG_INCLUDE_DIR}" STREQUAL "x${GTK2_${_var}_INCLUDE_DIR}")
             set_property(TARGET GTK2::${_basename} APPEND PROPERTY INTERFACE_INCLUDE_DIRECTORIES "${GTK2_${_var}CONFIG_INCLUDE_DIR}")
         endif()
 
@@ -540,7 +540,11 @@
         endif()
 
         if(_${_var}_OPTIONAL_INCLUDES)
-            _GTK2_ADD_TARGET_INCLUDE_DIRS(${_var} ${_${_var}_OPTIONAL_INCLUDES})
+            foreach(_D ${_${_var}_OPTIONAL_INCLUDES})
+                if(_D)
+                    _GTK2_ADD_TARGET_INCLUDE_DIRS(${_var} ${_D})
+                endif()
+            endforeach()
         endif()
 
         if(GTK2_USE_IMPORTED_TARGETS)
diff --git a/Modules/FindGettext.cmake b/Modules/FindGettext.cmake
index 7ab867b..16478cb 100644
--- a/Modules/FindGettext.cmake
+++ b/Modules/FindGettext.cmake
@@ -26,7 +26,7 @@
 #     ALL option is used, the translations will also be created when
 #     building the default target.
 #
-# GETTEXT_PROCESS_POT( <potfile> [ALL] [INSTALL_DESTINATION <destdir>]
+# GETTEXT_PROCESS_POT_FILE( <potfile> [ALL] [INSTALL_DESTINATION <destdir>]
 # LANGUAGES <lang1> <lang2> ...  )
 #
 # ::
diff --git a/Modules/FindHg.cmake b/Modules/FindHg.cmake
index c418afd..34d763e 100644
--- a/Modules/FindHg.cmake
+++ b/Modules/FindHg.cmake
@@ -66,7 +66,11 @@
   execute_process(COMMAND ${HG_EXECUTABLE} --version
                   OUTPUT_VARIABLE hg_version
                   ERROR_QUIET
+                  RESULT_VARIABLE hg_result
                   OUTPUT_STRIP_TRAILING_WHITESPACE)
+  if(hg_result MATCHES "is not a valid Win32 application")
+    set_property(CACHE HG_EXECUTABLE PROPERTY VALUE "HG_EXECUTABLE-NOTFOUND")
+  endif()
   if(hg_version MATCHES "^Mercurial Distributed SCM \\(version ([0-9][^)]*)\\)")
     set(HG_VERSION_STRING "${CMAKE_MATCH_1}")
   endif()
diff --git a/Modules/FindITK.cmake b/Modules/FindITK.cmake
deleted file mode 100644
index c9d39eb..0000000
--- a/Modules/FindITK.cmake
+++ /dev/null
@@ -1,61 +0,0 @@
-#.rst:
-# FindITK
-# -------
-#
-# Find an ITK installation or build tree.
-
-# When ITK is found, the ITKConfig.cmake file is sourced to setup the
-# location and configuration of ITK.  Please read this file, or
-# ITKConfig.cmake.in from the ITK source tree for the full list of
-# definitions.  Of particular interest is ITK_USE_FILE, a CMake source file
-# that can be included to set the include directories, library directories,
-# and preprocessor macros.  In addition to the variables read from
-# ITKConfig.cmake, this find module also defines
-#  ITK_DIR  - The directory containing ITKConfig.cmake.
-#             This is either the root of the build tree,
-#             or the lib/InsightToolkit directory.
-#             This is the only cache entry.
-#
-#  ITK_FOUND - Whether ITK was found.  If this is true,
-#              ITK_DIR is okay.
-#
-#  USE_ITK_FILE - The full path to the UseITK.cmake file.
-#                 This is provided for backward
-#                 compatibility.  Use ITK_USE_FILE
-#                 instead.
-
-#=============================================================================
-# Copyright 2001-2010 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
-# Use the Config mode of the find_package() command to find ITKConfig.
-# If this succeeds (possibly because ITK_DIR is already set), the
-# command will have already loaded ITKConfig.cmake and set ITK_FOUND.
-if(NOT ITK_FOUND)
-  set(_ITK_REQUIRED "")
-  if(ITK_FIND_REQUIRED)
-    set(_ITK_REQUIRED REQUIRED)
-  endif()
-  set(_ITK_QUIET "")
-  if(ITK_FIND_QUIETLY)
-    set(_ITK_QUIET QUIET)
-  endif()
-  find_package(ITK ${_ITK_REQUIRED} ${_ITK_QUIET} NO_MODULE
-    NAMES ITK InsightToolkit
-    CONFIGS ITKConfig.cmake
-    )
-endif()
-
-if(ITK_FOUND)
-  # Set USE_ITK_FILE for backward-compatibility.
-  set(USE_ITK_FILE ${ITK_USE_FILE})
-endif()
diff --git a/Modules/FindIce.cmake b/Modules/FindIce.cmake
new file mode 100644
index 0000000..55528b8
--- /dev/null
+++ b/Modules/FindIce.cmake
@@ -0,0 +1,393 @@
+#.rst:
+# FindIce
+# -------
+#
+# Find the ZeroC Internet Communication Engine (ICE) programs,
+# libraries and datafiles.
+#
+# This module supports multiple components.
+# Components can include any of: ``Freeze``, ``Glacier2``, ``Ice``,
+# ``IceBox``, ``IceDB``, ``IceGrid``, ``IcePatch``, ``IceSSL``,
+# ``IceStorm``, ``IceUtil``, ``IceXML``, or ``Slice``.
+#
+# This module reports information about the Ice installation in
+# several variables.  General variables::
+#
+#   Ice_VERSION - Ice release version
+#   Ice_FOUND - true if the main programs and libraries were found
+#   Ice_LIBRARIES - component libraries to be linked
+#   Ice_INCLUDE_DIRS - the directories containing the Ice headers
+#   Ice_SLICE_DIRS - the directories containing the Ice slice interface
+#                    definitions
+#
+# Ice programs are reported in::
+#
+#   Ice_SLICE2CPP_EXECUTABLE - path to slice2cpp executable
+#   Ice_SLICE2CS_EXECUTABLE - path to slice2cs executable
+#   Ice_SLICE2FREEZEJ_EXECUTABLE - path to slice2freezej executable
+#   Ice_SLICE2FREEZE_EXECUTABLE - path to slice2freeze executable
+#   Ice_SLICE2HTML_EXECUTABLE - path to slice2html executable
+#   Ice_SLICE2JAVA_EXECUTABLE - path to slice2java executable
+#   Ice_SLICE2PHP_EXECUTABLE - path to slice2php executable
+#   Ice_SLICE2PY_EXECUTABLE - path to slice2py executable
+#   Ice_SLICE2RB_EXECUTABLE - path to slice2rb executable
+#
+# Ice component libraries are reported in::
+#
+#   Ice_<C>_FOUND - ON if component was found
+#   Ice_<C>_LIBRARIES - libraries for component
+#
+# Note that ``<C>`` is the uppercased name of the component.
+#
+# This module reads hints about search results from::
+#
+#   Ice_HOME - the root of the Ice installation
+#
+# The environment variable :envvar:`ICE_HOME` may also be used; the
+# Ice_HOME variable takes precedence.
+#
+# The following cache variables may also be set::
+#
+#   Ice_<P>_EXECUTABLE - the path to executable <P>
+#   Ice_INCLUDE_DIR - the directory containing the Ice headers
+#   Ice_SLICE_DIR - the directory containing the Ice slice interface
+#                   definitions
+#   Ice_<C>_LIBRARY - the library for component <C>
+#
+# .. note::
+#
+#   In most cases none of the above variables will require setting,
+#   unless multiple Ice versions are available and a specific version
+#   is required.  On Windows, the most recent version of Ice will be
+#   found through the registry.  On Unix, the programs, headers and
+#   libraries will usually be in standard locations, but Ice_SLICE_DIRS
+#   might not be automatically detected (commonly known locations are
+#   searched).  All the other variables are defaulted using Ice_HOME,
+#   if set.  It's possible to set Ice_HOME and selectively specify
+#   alternative locations for the other components; this might be
+#   required for e.g. newer versions of Visual Studio if the
+#   heuristics are not sufficient to identify the correct programs and
+#   libraries for the specific Visual Studio version.
+#
+# Other variables one may set to control this module are::
+#
+#   Ice_DEBUG - Set to ON to enable debug output from FindIce.
+
+# Written by Roger Leigh <rleigh@codelibre.net>
+
+#=============================================================================
+# Copyright 2014 University of Dundee
+#
+# Distributed under the OSI-approved BSD License (the "License");
+# see accompanying file Copyright.txt for details.
+#
+# This software is distributed WITHOUT ANY WARRANTY; without even the
+# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+# See the License for more information.
+#=============================================================================
+# (To distribute this file outside of CMake, substitute the full
+#  License text for the above reference.)
+
+# The Ice checks are contained in a function due to the large number
+# of temporary variables needed.
+function(_Ice_FIND)
+  # Released versions of Ice, including generic short forms
+  set(ice_versions
+      3
+      3.5
+      3.5.1
+      3.5.0
+      3.4
+      3.4.2
+      3.4.1
+      3.4.0
+      3.3
+      3.3.1
+      3.3.0)
+
+  # Set up search paths, taking compiler into account.  Search Ice_HOME,
+  # with ICE_HOME in the environment as a fallback if unset.
+  if(Ice_HOME)
+    list(APPEND ice_roots "${Ice_HOME}")
+  else()
+    if(NOT "$ENV{ICE_HOME}" STREQUAL "")
+      file(TO_CMAKE_PATH "$ENV{ICE_HOME}" NATIVE_PATH)
+      list(APPEND ice_roots "${NATIVE_PATH}")
+      set(Ice_HOME "${NATIVE_PATH}"
+          CACHE PATH "Location of the Ice installation" FORCE)
+    endif()
+  endif()
+
+  if(CMAKE_SIZEOF_VOID_P EQUAL 8)
+    # 64-bit path suffix
+    set(_x64 "/x64")
+    # 64-bit library directory
+    set(_lib64 "lib64")
+  endif()
+
+  if(MSVC_VERSION)
+    # VS 8.0
+    if(NOT MSVC_VERSION VERSION_LESS 1400 AND MSVC_VERSION VERSION_LESS 1500)
+      set(vcver "vc80")
+      set(vcyear "2005")
+    # VS 9.0
+    elseif(NOT MSVC_VERSION VERSION_LESS 1500 AND MSVC_VERSION VERSION_LESS 1600)
+      set(vcver "vc90")
+      set(vcyear "2008")
+    # VS 10.0
+    elseif(NOT MSVC_VERSION VERSION_LESS 1600 AND MSVC_VERSION VERSION_LESS 1700)
+      set(vcver "vc100")
+    # VS 11.0
+    elseif(NOT MSVC_VERSION VERSION_LESS 1700 AND MSVC_VERSION VERSION_LESS 1800)
+      set(vcver "vc110")
+    # VS 12.0
+    elseif(NOT MSVC_VERSION VERSION_LESS 1800 AND MSVC_VERSION VERSION_LESS 1900)
+      set(vcver "vc120")
+    # VS 14.0
+    elseif(NOT MSVC_VERSION VERSION_LESS 1900 AND MSVC_VERSION VERSION_LESS 2000)
+      set(vcver "vc140")
+    endif()
+  endif()
+
+  # For compatibility with ZeroC Windows builds.
+  if(vcver)
+    # Earlier Ice (3.3) builds don't use vcnnn subdirectories, but are harmless to check.
+    list(APPEND ice_binary_suffixes "bin/${vcver}${_x64}" "bin/${vcver}")
+    list(APPEND ice_library_suffixes "lib/${vcver}${_x64}" "lib/${vcver}")
+  endif()
+  # Generic 64-bit and 32-bit directories
+  list(APPEND ice_binary_suffixes "bin${_x64}" "bin")
+  list(APPEND ice_library_suffixes "${_lib64}" "lib${_x64}" "lib")
+  list(APPEND ice_include_suffixes "include")
+  list(APPEND ice_slice_suffixes "slice")
+
+  # On Windows, look in the registry for install locations.  Different
+  # versions of Ice install support different compiler versions.
+  if(vcver)
+    foreach(ice_version ${ice_versions})
+      # Ice 3.3 releases use a Visual Studio year suffix and value is
+      # enclosed in double quotes, though only the leading quote is
+      # returned by get_filename_component.
+      unset(ice_location)
+      if(vcyear)
+        get_filename_component(ice_location
+                               "[HKEY_LOCAL_MACHINE\\SOFTWARE\\ZeroC\\Ice ${ice_version} for Visual Studio ${vcyear};InstallDir]"
+                               PATH)
+        if(ice_location AND NOT ("${ice_location}" STREQUAL "/registry" OR "${ice_location}" STREQUAL "/"))
+          string(REGEX REPLACE "^\"(.*)\"?$" "\\1" ice_location "${ice_location}")
+          get_filename_component(ice_location "${ice_location}" ABSOLUTE)
+        else()
+          unset(ice_location)
+        endif()
+      endif()
+      # Ice 3.4+ releases don't use a suffix
+      if(NOT ice_location OR "${ice_location}" STREQUAL "/registry")
+        get_filename_component(ice_location
+                               "[HKEY_LOCAL_MACHINE\\SOFTWARE\\ZeroC\\Ice ${ice_version};InstallDir]"
+                               ABSOLUTE)
+      endif()
+
+      if(ice_location AND NOT "${ice_location}" STREQUAL "/registry")
+        list(APPEND ice_roots "${ice_location}")
+      endif()
+    endforeach()
+  else()
+    foreach(ice_version ${ice_versions})
+      # Prefer 64-bit variants if present (and using a 64-bit compiler)
+      list(APPEND ice_roots "/opt/Ice-${ice_version}")
+    endforeach()
+  endif()
+
+  set(ice_programs
+      slice2cpp
+      slice2cs
+      slice2freezej
+      slice2freeze
+      slice2html
+      slice2java
+      slice2php
+      slice2py
+      slice2rb)
+
+  # Find all Ice programs
+  foreach(program ${ice_programs})
+    string(TOUPPER "${program}" program_upcase)
+    set(cache_var "Ice_${program_upcase}_EXECUTABLE")
+    set(program_var "Ice_${program_upcase}_EXECUTABLE")
+    find_program("${cache_var}" "${program}"
+      HINTS ${ice_roots}
+      PATH_SUFFIXES ${ice_binary_suffixes}
+      DOC "Ice ${program} executable")
+    mark_as_advanced(cache_var)
+    set("${program_var}" "${${cache_var}}" PARENT_SCOPE)
+  endforeach()
+
+  # Get version.
+  if(Ice_SLICE2CPP_EXECUTABLE)
+    # Execute in C locale for safety
+    set(_Ice_SAVED_LC_ALL "$ENV{LC_ALL}")
+    set(ENV{LC_ALL} C)
+
+    execute_process(COMMAND ${Ice_SLICE2CPP_EXECUTABLE} --version
+      ERROR_VARIABLE Ice_VERSION_SLICE2CPP_FULL
+      ERROR_STRIP_TRAILING_WHITESPACE)
+
+    # restore the previous LC_ALL
+    set(ENV{LC_ALL} ${_Ice_SAVED_LC_ALL})
+
+    # Make short version
+    string(REGEX REPLACE "^(.*)\\.[^.]*$" "\\1" Ice_VERSION_SLICE2CPP_SHORT "${Ice_VERSION_SLICE2CPP_FULL}")
+    set(Ice_VERSION "${Ice_VERSION_SLICE2CPP_FULL}" PARENT_SCOPE)
+  endif()
+
+  if(NOT Ice_FIND_QUIETLY)
+    message(STATUS "Ice version: ${Ice_VERSION_SLICE2CPP_FULL}")
+  endif()
+
+  # Find include directory
+  find_path(Ice_INCLUDE_DIR
+            NAMES "Ice/Ice.h"
+            HINTS ${ice_roots}
+            PATH_SUFFIXES ${ice_include_suffixes}
+            DOC "Ice include directory")
+  set(Ice_INCLUDE_DIR "${Ice_INCLUDE_DIR}" PARENT_SCOPE)
+
+  # In common use on Linux, MacOS X (homebrew) and FreeBSD; prefer
+  # version-specific dir
+  list(APPEND ice_slice_paths
+       /usr/local/share /usr/share)
+  list(APPEND ice_slice_suffixes
+       "Ice-${Ice_VERSION_SLICE2CPP_FULL}/slice"
+       "Ice-${Ice_VERSION_SLICE2CPP_SHORT}/slice"
+       Ice)
+
+  # Find slice directory
+  find_path(Ice_SLICE_DIR
+            NAMES "Ice/Connection.ice"
+            HINTS ${ice_roots}
+                  ${ice_slice_paths}
+            PATH_SUFFIXES ${ice_slice_suffixes}
+            NO_DEFAULT_PATH
+            DOC "Ice slice directory")
+  set(Ice_SLICE_DIR "${Ice_SLICE_DIR}" PARENT_SCOPE)
+
+  # Find all Ice libraries
+  set(Ice_REQUIRED_LIBS_FOUND ON)
+  foreach(component ${Ice_FIND_COMPONENTS})
+    string(TOUPPER "${component}" component_upcase)
+    set(component_cache "Ice_${component_upcase}_LIBRARY")
+    set(component_found "${component_upcase}_FOUND")
+    find_library("${component_cache}" "${component}"
+      HINTS ${ice_roots}
+      PATH_SUFFIXES ${ice_library_suffixes}
+      DOC "Ice ${component} library")
+    mark_as_advanced("${component_cache}")
+    if("${component_cache}")
+      set("${component_found}" ON)
+      list(APPEND Ice_LIBRARY "${${component_cache}}")
+    endif()
+    mark_as_advanced("${component_found}")
+    set("${component_cache}" "${${component_cache}}" PARENT_SCOPE)
+    set("${component_found}" "${${component_found}}" PARENT_SCOPE)
+    if("${component_found}")
+      if ("Ice_FIND_REQUIRED_${component}")
+        list(APPEND Ice_LIBS_FOUND "${component} (required)")
+      else()
+        list(APPEND Ice_LIBS_FOUND "${component} (optional)")
+      endif()
+    else()
+      if ("Ice_FIND_REQUIRED_${component}")
+        set(Ice_REQUIRED_LIBS_FOUND OFF)
+        list(APPEND Ice_LIBS_NOTFOUND "${component} (required)")
+      else()
+        list(APPEND Ice_LIBS_NOTFOUND "${component} (optional)")
+      endif()
+    endif()
+  endforeach()
+  set(_Ice_REQUIRED_LIBS_FOUND "${Ice_REQUIRED_LIBS_FOUND}" PARENT_SCOPE)
+  set(Ice_LIBRARY "${Ice_LIBRARY}" PARENT_SCOPE)
+
+  if(NOT Ice_FIND_QUIETLY)
+    if(Ice_LIBS_FOUND)
+      message(STATUS "Found the following Ice libraries:")
+      foreach(found ${Ice_LIBS_FOUND})
+        message(STATUS "  ${found}")
+      endforeach()
+    endif()
+    if(Ice_LIBS_NOTFOUND)
+      message(STATUS "The following Ice libraries were not found:")
+      foreach(notfound ${Ice_LIBS_NOTFOUND})
+        message(STATUS "  ${notfound}")
+      endforeach()
+    endif()
+  endif()
+
+  if(Ice_DEBUG)
+    message(STATUS "--------FindIce.cmake search debug--------")
+    message(STATUS "ICE binary path search order: ${ice_roots}")
+    message(STATUS "ICE include path search order: ${ice_roots}")
+    message(STATUS "ICE slice path search order: ${ice_roots} ${ice_slice_paths}")
+    message(STATUS "ICE library path search order: ${ice_roots}")
+    message(STATUS "----------------")
+  endif()
+endfunction()
+
+_Ice_FIND()
+
+include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
+FIND_PACKAGE_HANDLE_STANDARD_ARGS(Ice
+                                  FOUND_VAR Ice_FOUND
+                                  REQUIRED_VARS Ice_SLICE2CPP_EXECUTABLE
+                                                Ice_INCLUDE_DIR
+                                                Ice_SLICE_DIR
+                                                Ice_LIBRARY
+                                                _Ice_REQUIRED_LIBS_FOUND
+                                  VERSION_VAR Ice_VERSION
+                                  FAIL_MESSAGE "Failed to find all Ice components")
+
+unset(_Ice_REQUIRED_LIBS_FOUND)
+
+if(Ice_FOUND)
+  set(Ice_INCLUDE_DIRS "${Ice_INCLUDE_DIR}")
+  set(Ice_SLICE_DIRS "${Ice_SLICE_DIR}")
+  set(Ice_LIBRARIES "${Ice_LIBRARY}")
+  foreach(_Ice_component ${Ice_FIND_COMPONENTS})
+    string(TOUPPER "${_Ice_component}" _Ice_component_upcase)
+    set(_Ice_component_cache "Ice_${_Ice_component_upcase}_LIBRARY")
+    set(_Ice_component_lib "Ice_${_Ice_component_upcase}_LIBRARIES")
+    set(_Ice_component_found "${_Ice_component_upcase}_FOUND")
+    if("${_Ice_component_found}")
+      set("${_Ice_component_lib}" "${${_Ice_component_cache}}")
+    endif()
+    unset(_Ice_component_upcase)
+    unset(_Ice_component_cache)
+    unset(_Ice_component_lib)
+    unset(_Ice_component_found)
+  endforeach()
+endif()
+
+if(Ice_DEBUG)
+  message(STATUS "--------FindIce.cmake results debug--------")
+  message(STATUS "Ice_VERSION number: ${Ice_VERSION}")
+  message(STATUS "Ice_HOME directory: ${Ice_HOME}")
+  message(STATUS "Ice_INCLUDE_DIR directory: ${Ice_INCLUDE_DIR}")
+  message(STATUS "Ice_SLICE_DIR directory: ${Ice_SLICE_DIR}")
+  message(STATUS "Ice_LIBRARIES: ${Ice_LIBRARIES}")
+  message(STATUS "slice2cpp executable: ${Ice_SLICE2CPP_EXECUTABLE}")
+  message(STATUS "slice2cs executable: ${Ice_SLICE2CS_EXECUTABLE}")
+  message(STATUS "slice2freezej executable: ${Ice_SLICE2FREEZEJ_EXECUTABLE}")
+  message(STATUS "slice2freeze executable: ${Ice_SLICE2FREEZE_EXECUTABLE}")
+  message(STATUS "slice2html executable: ${Ice_SLICE2HTML_EXECUTABLE}")
+  message(STATUS "slice2java executable: ${Ice_SLICE2JAVA_EXECUTABLE}")
+  message(STATUS "slice2php executable: ${Ice_SLICE2PHP_EXECUTABLE}")
+  message(STATUS "slice2py executable: ${Ice_SLICE2PY_EXECUTABLE}")
+  message(STATUS "slice2rb executable: ${Ice_SLICE2RB_EXECUTABLE}")
+  foreach(component ${Ice_FIND_COMPONENTS})
+    string(TOUPPER "${component}" component_upcase)
+    set(component_lib "Ice_${component_upcase}_LIBRARIES")
+    set(component_found "${component_upcase}_FOUND")
+    message(STATUS "${component} library found: ${${component_found}}")
+    message(STATUS "${component} library: ${${component_lib}}")
+  endforeach()
+  message(STATUS "----------------")
+endif()
diff --git a/Modules/FindImageMagick.cmake b/Modules/FindImageMagick.cmake
index 4f0e687..65458b7 100644
--- a/Modules/FindImageMagick.cmake
+++ b/Modules/FindImageMagick.cmake
@@ -95,34 +95,68 @@
 # (To distribute this file outside of CMake, substitute the full
 #  License text for the above reference.)
 
+find_package(PkgConfig QUIET)
+
 #---------------------------------------------------------------------
 # Helper functions
 #---------------------------------------------------------------------
 function(FIND_IMAGEMAGICK_API component header)
   set(ImageMagick_${component}_FOUND FALSE PARENT_SCOPE)
 
+  pkg_check_modules(PC_${component} QUIET ${component})
+
   find_path(ImageMagick_${component}_INCLUDE_DIR
     NAMES ${header}
+    HINTS
+      ${PC_${component}_INCLUDEDIR}
+      ${PC_${component}_INCLUDE_DIRS}
     PATHS
       ${ImageMagick_INCLUDE_DIRS}
       "[HKEY_LOCAL_MACHINE\\SOFTWARE\\ImageMagick\\Current;BinPath]/include"
     PATH_SUFFIXES
       ImageMagick ImageMagick-6
-    DOC "Path to the ImageMagick include dir."
+    DOC "Path to the ImageMagick arch-independent include dir."
+    )
+  find_path(ImageMagick_${component}_ARCH_INCLUDE_DIR
+    NAMES magick/magick-baseconfig.h
+    HINTS
+      ${PC_${component}_INCLUDEDIR}
+      ${PC_${component}_INCLUDE_DIRS}
+    PATHS
+      ${ImageMagick_INCLUDE_DIRS}
+      "[HKEY_LOCAL_MACHINE\\SOFTWARE\\ImageMagick\\Current;BinPath]/include"
+    PATH_SUFFIXES
+      ImageMagick ImageMagick-6
+    DOC "Path to the ImageMagick arch-specific include dir."
     )
   find_library(ImageMagick_${component}_LIBRARY
     NAMES ${ARGN}
+    HINTS
+      ${PC_${component}_LIBDIR}
+      ${PC_${component}_LIB_DIRS}
     PATHS
       "[HKEY_LOCAL_MACHINE\\SOFTWARE\\ImageMagick\\Current;BinPath]/lib"
     DOC "Path to the ImageMagick Magick++ library."
     )
 
+  # old version have only indep dir
   if(ImageMagick_${component}_INCLUDE_DIR AND ImageMagick_${component}_LIBRARY)
     set(ImageMagick_${component}_FOUND TRUE PARENT_SCOPE)
 
-    list(APPEND ImageMagick_INCLUDE_DIRS
+    # Construct per-component include directories.
+    set(ImageMagick_${component}_INCLUDE_DIRS
       ${ImageMagick_${component}_INCLUDE_DIR}
       )
+    if(ImageMagick_${component}_ARCH_INCLUDE_DIR)
+      list(APPEND ImageMagick_${component}_INCLUDE_DIRS
+        ${ImageMagick_${component}_ARCH_INCLUDE_DIR})
+    endif()
+    list(REMOVE_DUPLICATES ImageMagick_${component}_INCLUDE_DIRS)
+    set(ImageMagick_${component}_INCLUDE_DIRS
+      ${ImageMagick_${component}_INCLUDE_DIRS} PARENT_SCOPE)
+
+    # Add the per-component include directories to the full include dirs.
+    list(APPEND ImageMagick_INCLUDE_DIRS ${ImageMagick_${component}_INCLUDE_DIRS})
     list(REMOVE_DUPLICATES ImageMagick_INCLUDE_DIRS)
     set(ImageMagick_INCLUDE_DIRS ${ImageMagick_INCLUDE_DIRS} PARENT_SCOPE)
 
diff --git a/Modules/FindJNI.cmake b/Modules/FindJNI.cmake
index 6a496af..3dcb0d0 100644
--- a/Modules/FindJNI.cmake
+++ b/Modules/FindJNI.cmake
@@ -55,7 +55,7 @@
         # endianess of the underlying system.
         set(_java_libarch "${CMAKE_SYSTEM_PROCESSOR}" "mips" "mipsel" "mipseb")
     elseif(CMAKE_SYSTEM_PROCESSOR MATCHES "^(powerpc|ppc)64le")
-        set(_java_libarch "ppc64le")
+        set(_java_libarch "ppc64" "ppc64le")
     elseif(CMAKE_SYSTEM_PROCESSOR MATCHES "^(powerpc|ppc)64")
         set(_java_libarch "ppc64" "ppc")
     elseif(CMAKE_SYSTEM_PROCESSOR MATCHES "^(powerpc|ppc)")
diff --git a/Modules/FindJPEG.cmake b/Modules/FindJPEG.cmake
index 90e4485..86bb6e5 100644
--- a/Modules/FindJPEG.cmake
+++ b/Modules/FindJPEG.cmake
@@ -33,7 +33,7 @@
 
 find_path(JPEG_INCLUDE_DIR jpeglib.h)
 
-set(JPEG_NAMES ${JPEG_NAMES} jpeg)
+set(JPEG_NAMES ${JPEG_NAMES} jpeg libjpeg)
 find_library(JPEG_LIBRARY NAMES ${JPEG_NAMES} )
 
 # handle the QUIETLY and REQUIRED arguments and set JPEG_FOUND to TRUE if
diff --git a/Modules/FindKDE3.cmake b/Modules/FindKDE3.cmake
index ea898a6..dda4530 100644
--- a/Modules/FindKDE3.cmake
+++ b/Modules/FindKDE3.cmake
@@ -8,29 +8,29 @@
 #
 # This module defines the following variables:
 #
-# ::
-#
-#   KDE3_DEFINITIONS         - compiler definitions required for compiling KDE software
-#   KDE3_INCLUDE_DIR         - the KDE include directory
-#   KDE3_INCLUDE_DIRS        - the KDE and the Qt include directory, for use with include_directories()
-#   KDE3_LIB_DIR             - the directory where the KDE libraries are installed, for use with link_directories()
-#   QT_AND_KDECORE_LIBS      - this contains both the Qt and the kdecore library
-#   KDE3_DCOPIDL_EXECUTABLE  - the dcopidl executable
-#   KDE3_DCOPIDL2CPP_EXECUTABLE - the dcopidl2cpp executable
-#   KDE3_KCFGC_EXECUTABLE    - the kconfig_compiler executable
-#   KDE3_FOUND               - set to TRUE if all of the above has been found
-#
-#
+# ``KDE3_DEFINITIONS``
+#   compiler definitions required for compiling KDE software
+# ``KDE3_INCLUDE_DIR``
+#   the KDE include directory
+# ``KDE3_INCLUDE_DIRS``
+#   the KDE and the Qt include directory, for use with include_directories()
+# ``KDE3_LIB_DIR``
+#   the directory where the KDE libraries are installed, for use with link_directories()
+# ``QT_AND_KDECORE_LIBS``
+#   this contains both the Qt and the kdecore library
+# ``KDE3_DCOPIDL_EXECUTABLE``
+#   the dcopidl executable
+# ``KDE3_DCOPIDL2CPP_EXECUTABLE``
+#   the dcopidl2cpp executable
+# ``KDE3_KCFGC_EXECUTABLE``
+#   the kconfig_compiler executable
+# ``KDE3_FOUND``
+#   set to TRUE if all of the above has been found
 #
 # The following user adjustable options are provided:
 #
-# ::
-#
-#   KDE3_BUILD_TESTS - enable this to build KDE testcases
-#
-#
-#
-#
+# ``KDE3_BUILD_TESTS``
+#   enable this to build KDE testcases
 #
 # It also adds the following macros (from KDE3Macros.cmake) SRCS_VAR is
 # always the variable which contains the list of source files for your
@@ -101,7 +101,8 @@
 #
 # ::
 #
-#     Currently identical to add_executable(), may provide some advanced features in the future.
+#     Currently identical to add_executable(), may provide some advanced
+#     features in the future.
 #
 #
 #
@@ -110,7 +111,8 @@
 # ::
 #
 #     Create a KDE plugin (KPart, kioslave, etc.) from the given source files.
-#     If WITH_PREFIX is given, the resulting plugin will have the prefix "lib", otherwise it won't.
+#     If WITH_PREFIX is given, the resulting plugin will have the prefix "lib",
+#     otherwise it won't.
 #     It creates and installs an appropriate libtool la-file.
 #
 #
@@ -120,7 +122,8 @@
 # ::
 #
 #     Create a KDE application in the form of a module loadable via kdeinit.
-#     A library named kdeinit_<name> will be created and a small executable which links to it.
+#     A library named kdeinit_<name> will be created and a small executable
+#     which links to it.
 #
 #
 #
diff --git a/Modules/FindLATEX.cmake b/Modules/FindLATEX.cmake
index 62eedd6..e353d38 100644
--- a/Modules/FindLATEX.cmake
+++ b/Modules/FindLATEX.cmake
@@ -104,7 +104,7 @@
 
 if (WIN32)
   find_program(PS2PDF_CONVERTER
-    NAMES ps2pdf14.bat ps2pdf
+    NAMES ps2pdf14.bat ps2pdf14 ps2pdf
     PATHS ${GHOSTSCRIPT_LIBRARY_PATH}
           ${MIKTEX_BINARY_PATH}
   )
diff --git a/Modules/FindLua.cmake b/Modules/FindLua.cmake
index cc35e54..731f5f2 100644
--- a/Modules/FindLua.cmake
+++ b/Modules/FindLua.cmake
@@ -56,7 +56,7 @@
 
     if (Lua_FIND_VERSION_EXACT)
         if (Lua_FIND_VERSION_COUNT GREATER 1)
-            set(lua_append_versions ${Lua_FIND_VERSION_MAJOR} ${Lua_FIND_VERSION_MINOR})
+            set(lua_append_versions ${Lua_FIND_VERSION_MAJOR}.${Lua_FIND_VERSION_MINOR})
         endif ()
     elseif (Lua_FIND_VERSION)
         # once there is a different major version supported this should become a loop
diff --git a/Modules/FindMPI.cmake b/Modules/FindMPI.cmake
index 6e15f3b..3be5e3c 100644
--- a/Modules/FindMPI.cmake
+++ b/Modules/FindMPI.cmake
@@ -522,6 +522,7 @@
 # Most mpi distros have some form of mpiexec which gives us something we can reliably look for.
 find_program(MPIEXEC
   NAMES ${_MPI_EXEC_NAMES}
+  HINTS ${MPI_HOME} $ENV{MPI_HOME}
   PATHS ${_MPI_PREFIX_PATH}
   PATH_SUFFIXES bin
   DOC "Executable for running MPI programs.")
@@ -584,7 +585,9 @@
 
     find_program(MPI_${lang}_COMPILER
       NAMES  ${_MPI_${lang}_COMPILER_NAMES}
-      PATHS  "${MPI_HOME}/bin" "$ENV{MPI_HOME}/bin" ${_MPI_PREFIX_PATH})
+      HINTS  ${_MPI_BASE_DIR}/bin
+      PATHS  ${_MPI_PREFIX_PATH}
+      )
     interrogate_mpi_compiler(${lang} ${try_libs})
     mark_as_advanced(MPI_${lang}_COMPILER)
 
diff --git a/Modules/FindOpenCL.cmake b/Modules/FindOpenCL.cmake
index b5eed9a..4d3ed84 100644
--- a/Modules/FindOpenCL.cmake
+++ b/Modules/FindOpenCL.cmake
@@ -70,14 +70,15 @@
 find_path(OpenCL_INCLUDE_DIR
   NAMES
     CL/cl.h OpenCL/cl.h
-  PATHS ENV
-    "PROGRAMFILES(X86)"
-    AMDAPPSDKROOT
-    INTELOCLSDKROOT
-    NVSDKCOMPUTE_ROOT
-    CUDA_PATH
-    ATISTREAMSDKROOT
+  PATHS
+    ENV "PROGRAMFILES(X86)"
+    ENV AMDAPPSDKROOT
+    ENV INTELOCLSDKROOT
+    ENV NVSDKCOMPUTE_ROOT
+    ENV CUDA_PATH
+    ENV ATISTREAMSDKROOT
   PATH_SUFFIXES
+    include
     OpenCL/common/inc
     "AMD APP/include")
 
@@ -87,13 +88,13 @@
   if(CMAKE_SIZEOF_VOID_P EQUAL 4)
     find_library(OpenCL_LIBRARY
       NAMES OpenCL
-      PATHS ENV
-        "PROGRAMFILES(X86)"
-        AMDAPPSDKROOT
-        INTELOCLSDKROOT
-        CUDA_PATH
-        NVSDKCOMPUTE_ROOT
-        ATISTREAMSDKROOT
+      PATHS
+        ENV "PROGRAMFILES(X86)"
+        ENV AMDAPPSDKROOT
+        ENV INTELOCLSDKROOT
+        ENV CUDA_PATH
+        ENV NVSDKCOMPUTE_ROOT
+        ENV ATISTREAMSDKROOT
       PATH_SUFFIXES
         "AMD APP/lib/x86"
         lib/x86
@@ -102,13 +103,13 @@
   elseif(CMAKE_SIZEOF_VOID_P EQUAL 8)
     find_library(OpenCL_LIBRARY
       NAMES OpenCL
-      PATHS ENV
-        "PROGRAMFILES(X86)"
-        AMDAPPSDKROOT
-        INTELOCLSDKROOT
-        CUDA_PATH
-        NVSDKCOMPUTE_ROOT
-        ATISTREAMSDKROOT
+      PATHS
+        ENV "PROGRAMFILES(X86)"
+        ENV AMDAPPSDKROOT
+        ENV INTELOCLSDKROOT
+        ENV CUDA_PATH
+        ENV NVSDKCOMPUTE_ROOT
+        ENV ATISTREAMSDKROOT
       PATH_SUFFIXES
         "AMD APP/lib/x86_64"
         lib/x86_64
diff --git a/Modules/FindOpenMP.cmake b/Modules/FindOpenMP.cmake
index 30972ae..801b4f8 100644
--- a/Modules/FindOpenMP.cmake
+++ b/Modules/FindOpenMP.cmake
@@ -16,6 +16,7 @@
 #
 #    OpenMP_C_FLAGS - flags to add to the C compiler for OpenMP support
 #    OpenMP_CXX_FLAGS - flags to add to the CXX compiler for OpenMP support
+#    OpenMP_Fortran_FLAGS - flags to add to the Fortran compiler for OpenMP support
 #    OPENMP_FOUND - true if openmp is detected
 #
 #
@@ -27,6 +28,7 @@
 # Copyright 2009 Kitware, Inc.
 # Copyright 2008-2009 André Rigland Brodtkorb <Andre.Brodtkorb@ifi.uio.no>
 # Copyright 2012 Rolf Eike Beer <eike@sf-mail.de>
+# Copyright 2014 Nicolas Bock <nicolasbock@gmail.com>
 #
 # Distributed under the OSI-approved BSD License (the "License");
 # see accompanying file Copyright.txt for details.
@@ -68,8 +70,11 @@
   set(OMP_FLAG_HP "+Oopenmp")
   if(WIN32)
     set(OMP_FLAG_Intel "-Qopenmp")
-  else()
+  elseif(CMAKE_${LANG}_COMPILER_ID STREQUAL "Intel" AND
+         "${CMAKE_${LANG}_COMPILER_VERSION}" VERSION_LESS "15.0.0.20140528")
     set(OMP_FLAG_Intel "-openmp")
+  else()
+    set(OMP_FLAG_Intel "-qopenmp")
   endif()
   set(OMP_FLAG_MIPSpro "-mp")
   set(OMP_FLAG_MSVC "/openmp")
@@ -103,6 +108,17 @@
 }
 ")
 
+# same in Fortran
+set(OpenMP_Fortran_TEST_SOURCE
+  "
+program test
+use omp_lib
+integer :: n
+n = omp_get_num_threads()
+end program test
+  "
+  )
+
 # check c compiler
 if(CMAKE_C_COMPILER_LOADED)
   # if these are set then do not try to find them again,
@@ -173,6 +189,40 @@
   unset(OpenMP_CXX_TEST_SOURCE)
 endif()
 
+# check Fortran compiler
+if(CMAKE_Fortran_COMPILER_LOADED)
+  # if these are set then do not try to find them again,
+  # by avoiding any try_compiles for the flags
+  if(OpenMP_Fortran_FLAGS)
+    unset(OpenMP_Fortran_FLAG_CANDIDATES)
+  else()
+    _OPENMP_FLAG_CANDIDATES("Fortran")
+    include(${CMAKE_CURRENT_LIST_DIR}/CheckFortranSourceCompiles.cmake)
+  endif()
+
+  foreach(FLAG IN LISTS OpenMP_Fortran_FLAG_CANDIDATES)
+    set(SAFE_CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS}")
+    set(CMAKE_REQUIRED_FLAGS "${FLAG}")
+    unset(OpenMP_FLAG_DETECTED CACHE)
+    if(NOT CMAKE_REQUIRED_QUIET)
+      message(STATUS "Try OpenMP Fortran flag = [${FLAG}]")
+    endif()
+    check_fortran_source_compiles("${OpenMP_Fortran_TEST_SOURCE}" OpenMP_FLAG_DETECTED)
+    set(CMAKE_REQUIRED_FLAGS "${SAFE_CMAKE_REQUIRED_FLAGS}")
+    if(OpenMP_FLAG_DETECTED)
+      set(OpenMP_Fortran_FLAGS_INTERNAL "${FLAG}")
+      break()
+    endif()
+  endforeach()
+
+  set(OpenMP_Fortran_FLAGS "${OpenMP_Fortran_FLAGS_INTERNAL}"
+    CACHE STRING "Fortran compiler flags for OpenMP parallization")
+
+  list(APPEND _OPENMP_REQUIRED_VARS OpenMP_Fortran_FLAGS)
+  unset(OpenMP_Fortran_FLAG_CANDIDATES)
+  unset(OpenMP_Fortran_TEST_SOURCE)
+endif()
+
 set(CMAKE_REQUIRED_QUIET ${CMAKE_REQUIRED_QUIET_SAVE})
 
 if(_OPENMP_REQUIRED_VARS)
diff --git a/Modules/FindOpenSceneGraph.cmake b/Modules/FindOpenSceneGraph.cmake
index 7bbd753..5a800e4 100644
--- a/Modules/FindOpenSceneGraph.cmake
+++ b/Modules/FindOpenSceneGraph.cmake
@@ -40,13 +40,14 @@
 # OSG and it's various components.  CMAKE_PREFIX_PATH can also be used
 # for this (see find_library() CMake documentation).
 #
-# ::
-#
-#     <MODULE>_DIR (where MODULE is of the form "OSGVOLUME" and there is a FindosgVolume.cmake file)
-#     OSG_DIR
-#     OSGDIR
-#     OSG_ROOT
-#
+# ``<MODULE>_DIR``
+#   (where MODULE is of the form "OSGVOLUME" and there is a FindosgVolume.cmake file)
+# ``OSG_DIR``
+#   ..
+# ``OSGDIR``
+#   ..
+# ``OSG_ROOT``
+#   ..
 #
 #
 # [CMake 2.8.10]: The CMake variable OSG_DIR can now be used as well to
@@ -203,8 +204,11 @@
     find_package(${_osg_module} ${_osg_quiet})
 
     string(TOUPPER ${_osg_module} _osg_module_UC)
-    list(APPEND OPENSCENEGRAPH_INCLUDE_DIR ${${_osg_module_UC}_INCLUDE_DIR})
-    list(APPEND OPENSCENEGRAPH_LIBRARIES ${${_osg_module_UC}_LIBRARIES})
+    # append to list if module was found OR is required
+    if( ${_osg_module_UC}_FOUND OR OpenSceneGraph_FIND_REQUIRED )
+      list(APPEND OPENSCENEGRAPH_INCLUDE_DIR ${${_osg_module_UC}_INCLUDE_DIR})
+      list(APPEND OPENSCENEGRAPH_LIBRARIES ${${_osg_module_UC}_LIBRARIES})
+    endif()
 
     if(OpenSceneGraph_MARK_AS_ADVANCED)
         OSG_MARK_AS_ADVANCED(${_osg_module})
diff --git a/Modules/FindPNG.cmake b/Modules/FindPNG.cmake
index fa04bf0..7cf3f22 100644
--- a/Modules/FindPNG.cmake
+++ b/Modules/FindPNG.cmake
@@ -10,19 +10,22 @@
 #
 # It defines the following variables
 #
-# ::
-#
-#   PNG_INCLUDE_DIRS, where to find png.h, etc.
-#   PNG_LIBRARIES, the libraries to link against to use PNG.
-#   PNG_DEFINITIONS - You should add_definitons(${PNG_DEFINITIONS}) before compiling code that includes png library files.
-#   PNG_FOUND, If false, do not try to use PNG.
-#   PNG_VERSION_STRING - the version of the PNG library found (since CMake 2.8.8)
+# ``PNG_INCLUDE_DIRS``
+#   where to find png.h, etc.
+# ``PNG_LIBRARIES``
+#   the libraries to link against to use PNG.
+# ``PNG_DEFINITIONS``
+#   You should add_definitons(${PNG_DEFINITIONS}) before compiling code
+#   that includes png library files.
+# ``PNG_FOUND``
+#   If false, do not try to use PNG.
+# ``PNG_VERSION_STRING``
+#   the version of the PNG library found (since CMake 2.8.8)
 #
 # Also defined, but not for general use are
 #
-# ::
-#
-#   PNG_LIBRARY, where to find the PNG library.
+# ``PNG_LIBRARY``
+#   where to find the PNG library.
 #
 # For backward compatiblity the variable PNG_INCLUDE_DIR is also set.
 # It has the same value as PNG_INCLUDE_DIRS.
diff --git a/Modules/FindPackageHandleStandardArgs.cmake b/Modules/FindPackageHandleStandardArgs.cmake
index d030418..6bcf1e7 100644
--- a/Modules/FindPackageHandleStandardArgs.cmake
+++ b/Modules/FindPackageHandleStandardArgs.cmake
@@ -20,7 +20,8 @@
 #
 # ::
 #
-#     FIND_PACKAGE_HANDLE_STANDARD_ARGS(<name> (DEFAULT_MSG|"Custom failure message") <var1>...<varN> )
+#     FIND_PACKAGE_HANDLE_STANDARD_ARGS(<name>
+#       (DEFAULT_MSG|"Custom failure message") <var1>...<varN> )
 #
 # If the variables <var1> to <varN> are all valid, then
 # <UPPERCASED_NAME>_FOUND will be set to TRUE.  If DEFAULT_MSG is given
@@ -32,14 +33,13 @@
 #
 # ::
 #
-#     FIND_PACKAGE_HANDLE_STANDARD_ARGS(NAME [FOUND_VAR <resultVar>]
-#                                            [REQUIRED_VARS <var1>...<varN>]
-#                                            [VERSION_VAR   <versionvar>]
-#                                            [HANDLE_COMPONENTS]
-#                                            [CONFIG_MODE]
-#                                            [FAIL_MESSAGE "Custom failure message"] )
-#
-#
+#     FIND_PACKAGE_HANDLE_STANDARD_ARGS(NAME
+#       [FOUND_VAR <resultVar>]
+#       [REQUIRED_VARS <var1>...<varN>]
+#       [VERSION_VAR   <versionvar>]
+#       [HANDLE_COMPONENTS]
+#       [CONFIG_MODE]
+#       [FAIL_MESSAGE "Custom failure message"] )
 #
 # In this mode, the name of the result-variable can be set either to
 # either <UPPERCASED_NAME>_FOUND or <OriginalCase_Name>_FOUND using the
@@ -75,7 +75,8 @@
 #
 # ::
 #
-#     find_package_handle_standard_args(LibXml2  DEFAULT_MSG  LIBXML2_LIBRARY LIBXML2_INCLUDE_DIR)
+#     find_package_handle_standard_args(LibXml2  DEFAULT_MSG
+#       LIBXML2_LIBRARY LIBXML2_INCLUDE_DIR)
 #
 #
 #
@@ -90,9 +91,10 @@
 #
 # ::
 #
-#     find_package_handle_standard_args(LibXslt FOUND_VAR LibXslt_FOUND
-#                                              REQUIRED_VARS LibXslt_LIBRARIES LibXslt_INCLUDE_DIRS
-#                                              VERSION_VAR LibXslt_VERSION_STRING)
+#     find_package_handle_standard_args(LibXslt
+#       FOUND_VAR LibXslt_FOUND
+#       REQUIRED_VARS LibXslt_LIBRARIES LibXslt_INCLUDE_DIRS
+#       VERSION_VAR LibXslt_VERSION_STRING)
 #
 # In this case, LibXslt is considered to be found if the variable(s)
 # listed after REQUIRED_VAR are all valid, i.e.  LibXslt_LIBRARIES and
@@ -201,7 +203,7 @@
 
 # now that we collected all arguments, process them
 
-  if("${FPHSA_FAIL_MESSAGE}" STREQUAL "DEFAULT_MSG")
+  if("x${FPHSA_FAIL_MESSAGE}" STREQUAL "xDEFAULT_MSG")
     set(FPHSA_FAIL_MESSAGE "Could NOT find ${_NAME}")
   endif()
 
@@ -284,18 +286,47 @@
   # version handling:
   set(VERSION_MSG "")
   set(VERSION_OK TRUE)
-  set(VERSION ${${FPHSA_VERSION_VAR}} )
-  if (${_NAME}_FIND_VERSION)
+  set(VERSION ${${FPHSA_VERSION_VAR}})
 
-    if(VERSION)
+  # check with DEFINED here as the requested or found version may be "0"
+  if (DEFINED ${_NAME}_FIND_VERSION)
+    if(DEFINED ${FPHSA_VERSION_VAR})
 
       if(${_NAME}_FIND_VERSION_EXACT)       # exact version required
-        if (NOT "${${_NAME}_FIND_VERSION}" VERSION_EQUAL "${VERSION}")
-          set(VERSION_MSG "Found unsuitable version \"${VERSION}\", but required is exact version \"${${_NAME}_FIND_VERSION}\"")
-          set(VERSION_OK FALSE)
+        # count the dots in the version string
+        string(REGEX REPLACE "[^.]" "" _VERSION_DOTS "${VERSION}")
+        # add one dot because there is one dot more than there are components
+        string(LENGTH "${_VERSION_DOTS}." _VERSION_DOTS)
+        if (_VERSION_DOTS GREATER ${_NAME}_FIND_VERSION_COUNT)
+          # Because of the C++ implementation of find_package() ${_NAME}_FIND_VERSION_COUNT
+          # is at most 4 here. Therefore a simple lookup table is used.
+          if (${_NAME}_FIND_VERSION_COUNT EQUAL 1)
+            set(_VERSION_REGEX "[^.]*")
+          elseif (${_NAME}_FIND_VERSION_COUNT EQUAL 2)
+            set(_VERSION_REGEX "[^.]*\\.[^.]*")
+          elseif (${_NAME}_FIND_VERSION_COUNT EQUAL 3)
+            set(_VERSION_REGEX "[^.]*\\.[^.]*\\.[^.]*")
+          else ()
+            set(_VERSION_REGEX "[^.]*\\.[^.]*\\.[^.]*\\.[^.]*")
+          endif ()
+          string(REGEX REPLACE "^(${_VERSION_REGEX})\\..*" "\\1" _VERSION_HEAD "${VERSION}")
+          unset(_VERSION_REGEX)
+          if (NOT ${_NAME}_FIND_VERSION VERSION_EQUAL _VERSION_HEAD)
+            set(VERSION_MSG "Found unsuitable version \"${VERSION}\", but required is exact version \"${${_NAME}_FIND_VERSION}\"")
+            set(VERSION_OK FALSE)
+          else ()
+            set(VERSION_MSG "(found suitable exact version \"${VERSION}\")")
+          endif ()
+          unset(_VERSION_HEAD)
         else ()
-          set(VERSION_MSG "(found suitable exact version \"${VERSION}\")")
+          if (NOT "${${_NAME}_FIND_VERSION}" VERSION_EQUAL "${VERSION}")
+            set(VERSION_MSG "Found unsuitable version \"${VERSION}\", but required is exact version \"${${_NAME}_FIND_VERSION}\"")
+            set(VERSION_OK FALSE)
+          else ()
+            set(VERSION_MSG "(found suitable exact version \"${VERSION}\")")
+          endif ()
         endif ()
+        unset(_VERSION_DOTS)
 
       else()     # minimum version specified:
         if ("${${_NAME}_FIND_VERSION}" VERSION_GREATER "${VERSION}")
diff --git a/Modules/FindPostgreSQL.cmake b/Modules/FindPostgreSQL.cmake
index f13dea8..97666c8 100644
--- a/Modules/FindPostgreSQL.cmake
+++ b/Modules/FindPostgreSQL.cmake
@@ -145,12 +145,22 @@
 )
 get_filename_component(PostgreSQL_LIBRARY_DIR ${PostgreSQL_LIBRARY} PATH)
 
-if (PostgreSQL_INCLUDE_DIR AND EXISTS "${PostgreSQL_INCLUDE_DIR}/pg_config.h")
-  file(STRINGS "${PostgreSQL_INCLUDE_DIR}/pg_config.h" pgsql_version_str
-       REGEX "^#define[\t ]+PG_VERSION[\t ]+\".*\"")
-
-  string(REGEX REPLACE "^#define[\t ]+PG_VERSION[\t ]+\"([^\"]*)\".*" "\\1"
-         PostgreSQL_VERSION_STRING "${pgsql_version_str}")
+if (PostgreSQL_INCLUDE_DIR)
+  # Some platforms include multiple pg_config.hs for multi-lib configurations
+  # This is a temporary workaround.  A better solution would be to compile
+  # a dummy c file and extract the value of the symbol.
+  file(GLOB _PG_CONFIG_HEADERS "${PostgreSQL_INCLUDE_DIR}/pg_config*.h")
+  foreach(_PG_CONFIG_HEADER ${_PG_CONFIG_HEADERS})
+    if(EXISTS "${_PG_CONFIG_HEADER}")
+      file(STRINGS "${_PG_CONFIG_HEADER}" pgsql_version_str
+           REGEX "^#define[\t ]+PG_VERSION[\t ]+\".*\"")
+      if(pgsql_version_str)
+        string(REGEX REPLACE "^#define[\t ]+PG_VERSION[\t ]+\"([^\"]*)\".*"
+               "\\1" PostgreSQL_VERSION_STRING "${pgsql_version_str}")
+        break()
+      endif()
+    endif()
+  endforeach()
   unset(pgsql_version_str)
 endif()
 
diff --git a/Modules/FindProtobuf.cmake b/Modules/FindProtobuf.cmake
index 9b120a6..72ca6ed 100644
--- a/Modules/FindProtobuf.cmake
+++ b/Modules/FindProtobuf.cmake
@@ -183,7 +183,7 @@
              "${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}.pb.h"
       COMMAND  ${PROTOBUF_PROTOC_EXECUTABLE}
       ARGS --cpp_out  ${CMAKE_CURRENT_BINARY_DIR} ${_protobuf_include_path} ${ABS_FIL}
-      DEPENDS ${ABS_FIL}
+      DEPENDS ${ABS_FIL} ${PROTOBUF_PROTOC_EXECUTABLE}
       COMMENT "Running C++ protocol buffer compiler on ${FIL}"
       VERBATIM )
   endforeach()
diff --git a/Modules/FindQt4.cmake b/Modules/FindQt4.cmake
index c930042..2c39de5 100644
--- a/Modules/FindQt4.cmake
+++ b/Modules/FindQt4.cmake
@@ -111,12 +111,14 @@
 #
 # ::
 #
-#   macro QT4_ADD_DBUS_ADAPTOR(outfiles xmlfile parentheader parentclassname [basename] [classname])
+#   macro QT4_ADD_DBUS_ADAPTOR(outfiles xmlfile parentheader parentclassname
+#                              [basename] [classname])
 #         create a dbus adaptor (header and implementation file) from the xml file
 #         describing the interface, and add it to the list of sources. The adaptor
 #         forwards the calls to a parent class, defined in parentheader and named
 #         parentclassname. The name of the generated files will be
-#         <basename>adaptor.{cpp,h} where basename defaults to the basename of the xml file.
+#         <basename>adaptor.{cpp,h} where basename defaults to the basename of the
+#         xml file.
 #         If <classname> is provided, then it will be used as the classname of the
 #         adaptor itself.
 #
@@ -128,7 +130,8 @@
 #         If the optional argument interfacename is omitted, the name of the
 #         interface file is constructed from the basename of the header with
 #         the suffix .xml appended.
-#         Options may be given to qdbuscpp2xml, such as those found when executing "qdbuscpp2xml --help"
+#         Options may be given to qdbuscpp2xml, such as those found when
+#         executing "qdbuscpp2xml --help"
 #
 #
 # ::
@@ -170,10 +173,11 @@
 #         want to use QT4_WRAP_CPP() (which is reliable and mature), you can insert
 #         #include "foo.moc"
 #         in foo.cpp and then give foo.cpp as argument to QT4_AUTOMOC(). This will the
-#         scan all listed files at cmake-time for such included moc files and if it finds
-#         them cause a rule to be generated to run moc at build time on the
+#         scan all listed files at cmake-time for such included moc files and if it
+#         finds them cause a rule to be generated to run moc at build time on the
 #         accompanying header file foo.h.
-#         If a source file has the SKIP_AUTOMOC property set it will be ignored by this macro.
+#         If a source file has the SKIP_AUTOMOC property set it will be ignored by
+#         this macro.
 #         If the <tgt> is specified, the INTERFACE_INCLUDE_DIRECTORIES and
 #         INTERFACE_COMPILE_DEFINITIONS from the <tgt> are passed to moc.
 #
@@ -181,16 +185,17 @@
 # ::
 #
 #  function QT4_USE_MODULES( target [link_type] modules...)
-#         This function is obsolete. Use target_link_libraries with IMPORTED targets instead.
+#         This function is obsolete. Use target_link_libraries with IMPORTED targets
+#         instead.
 #         Make <target> use the <modules> from Qt. Using a Qt module means
 #         to link to the library, add the relevant include directories for the module,
 #         and add the relevant compiler defines for using the module.
 #         Modules are roughly equivalent to components of Qt4, so usage would be
 #         something like:
 #          qt4_use_modules(myexe Core Gui Declarative)
-#         to use QtCore, QtGui and QtDeclarative. The optional <link_type> argument can
-#         be specified as either LINK_PUBLIC or LINK_PRIVATE to specify the same argument
-#         to the target_link_libraries call.
+#         to use QtCore, QtGui and QtDeclarative. The optional <link_type> argument
+#         can be specified as either LINK_PUBLIC or LINK_PRIVATE to specify the
+#         same argument to the target_link_libraries call.
 #
 #
 # IMPORTED Targets
@@ -518,7 +523,8 @@
 set(_QT4_QMAKE_NAMES qmake qmake4 qmake-qt4 qmake-mac)
 _qt4_find_qmake("${_QT4_QMAKE_NAMES}" QT_QMAKE_EXECUTABLE QTVERSION)
 
-if (QT_QMAKE_EXECUTABLE AND QTVERSION)
+if (QT_QMAKE_EXECUTABLE AND
+  QTVERSION VERSION_GREATER 3 AND QTVERSION VERSION_LESS 5)
 
   if (Qt5Core_FOUND)
     # Qt5CoreConfig sets QT_MOC_EXECUTABLE as a non-cache variable to the Qt 5
@@ -1192,14 +1198,14 @@
   set( QT_PLUGIN_TYPES accessible bearer codecs decorations designer gfxdrivers graphicssystems iconengines imageformats inputmethods mousedrivers phonon_backend script sqldrivers )
 
   set( QT_ACCESSIBLE_PLUGINS qtaccessiblecompatwidgets qtaccessiblewidgets )
-  set( QT_BEARER_PLUGINS qcorewlanbearer qgenericbearer )
+  set( QT_BEARER_PLUGINS qcorewlanbearer qgenericbearer qnativewifibearer )
   set( QT_CODECS_PLUGINS qcncodecs qjpcodecs qkrcodecs qtwcodecs )
   set( QT_DECORATIONS_PLUGINS qdecorationdefault qdecorationwindows )
   set( QT_DESIGNER_PLUGINS arthurplugin containerextension customwidgetplugin phononwidgets qdeclarativeview qt3supportwidgets qwebview taskmenuextension worldtimeclockplugin )
   set( QT_GRAPHICSDRIVERS_PLUGINS qgfxtransformed qgfxvnc qscreenvfb )
   set( QT_GRAPHICSSYSTEMS_PLUGINS qglgraphicssystem qtracegraphicssystem )
   set( QT_ICONENGINES_PLUGINS qsvgicon )
-  set( QT_IMAGEFORMATS_PLUGINS qgif qjpeg qmng qico qsvg qtiff  )
+  set( QT_IMAGEFORMATS_PLUGINS qgif qjpeg qmng qico qsvg qtiff qtga )
   set( QT_INPUTMETHODS_PLUGINS qimsw_multi )
   set( QT_MOUSEDRIVERS_PLUGINS qwstslibmousehandler )
   if(APPLE)
@@ -1213,7 +1219,7 @@
   set( QT_PHONON_PLUGINS ${QT_PHONON_BACKEND_PLUGINS} )
   set( QT_QT3SUPPORT_PLUGINS qtaccessiblecompatwidgets )
   set( QT_QTCORE_PLUGINS ${QT_BEARER_PLUGINS} ${QT_CODECS_PLUGINS} )
-  set( QT_QTGUI_PLUGINS qtaccessiblewidgets qgif qjpeg qmng qico qtiff ${QT_DECORATIONS_PLUGINS} ${QT_GRAPHICSDRIVERS_PLUGINS} ${QT_GRAPHICSSYSTEMS_PLUGINS} ${QT_INPUTMETHODS_PLUGINS} ${QT_MOUSEDRIVERS_PLUGINS} )
+  set( QT_QTGUI_PLUGINS qtaccessiblewidgets ${QT_IMAGEFORMATS_PLUGINS} ${QT_DECORATIONS_PLUGINS} ${QT_GRAPHICSDRIVERS_PLUGINS} ${QT_GRAPHICSSYSTEMS_PLUGINS} ${QT_INPUTMETHODS_PLUGINS} ${QT_MOUSEDRIVERS_PLUGINS} )
   set( QT_QTSCRIPT_PLUGINS ${QT_SCRIPT_PLUGINS} )
   set( QT_QTSQL_PLUGINS ${QT_SQLDRIVERS_PLUGINS} )
   set( QT_QTSVG_PLUGINS qsvg qsvgicon )
diff --git a/Modules/FindRuby.cmake b/Modules/FindRuby.cmake
index aafdc09..b5ac703 100644
--- a/Modules/FindRuby.cmake
+++ b/Modules/FindRuby.cmake
@@ -14,19 +14,21 @@
 # It also determines what the name of the library is.  This code sets
 # the following variables:
 #
-# ::
+# ``RUBY_EXECUTABLE``
+#   full path to the ruby binary
+# ``RUBY_INCLUDE_DIRS``
+#   include dirs to be used when using the ruby library
+# ``RUBY_LIBRARY``
+#   full path to the ruby library
+# ``RUBY_VERSION``
+#   the version of ruby which was found, e.g. "1.8.7"
+# ``RUBY_FOUND``
+#   set to true if ruby ws found successfully
 #
-#   RUBY_EXECUTABLE   = full path to the ruby binary
-#   RUBY_INCLUDE_DIRS = include dirs to be used when using the ruby library
-#   RUBY_LIBRARY      = full path to the ruby library
-#   RUBY_VERSION      = the version of ruby which was found, e.g. "1.8.7"
-#   RUBY_FOUND        = set to true if ruby ws found successfully
+# Also:
 #
-#
-#
-# ::
-#
-#   RUBY_INCLUDE_PATH = same as RUBY_INCLUDE_DIRS, only provided for compatibility reasons, don't use it
+# ``RUBY_INCLUDE_PATH``
+#   same as RUBY_INCLUDE_DIRS, only provided for compatibility reasons, don't use it
 
 #=============================================================================
 # Copyright 2004-2009 Kitware, Inc.
diff --git a/Modules/FindSWIG.cmake b/Modules/FindSWIG.cmake
index 8bd4048..818d1f2 100644
--- a/Modules/FindSWIG.cmake
+++ b/Modules/FindSWIG.cmake
@@ -25,6 +25,7 @@
 #=============================================================================
 # Copyright 2004-2009 Kitware, Inc.
 # Copyright 2011 Mathieu Malaterre <mathieu.malaterre@gmail.com>
+# Copyright 2014 Sylvain Joubert <joubert.sy@gmail.com>
 #
 # Distributed under the OSI-approved BSD License (the "License");
 # see accompanying file Copyright.txt for details.
@@ -36,7 +37,7 @@
 # (To distribute this file outside of CMake, substitute the full
 #  License text for the above reference.)
 
-find_program(SWIG_EXECUTABLE NAMES swig2.0 swig)
+find_program(SWIG_EXECUTABLE NAMES swig3.0 swig2.0 swig)
 
 if(SWIG_EXECUTABLE)
   execute_process(COMMAND ${SWIG_EXECUTABLE} -swiglib
diff --git a/Modules/FindSquish.cmake b/Modules/FindSquish.cmake
index 4076521..4fdecb4 100644
--- a/Modules/FindSquish.cmake
+++ b/Modules/FindSquish.cmake
@@ -21,7 +21,8 @@
 #
 # ::
 #
-#   SQUISH_INSTALL_DIR              The Squish installation directory (containing bin, lib, etc)
+#   SQUISH_INSTALL_DIR              The Squish installation directory
+#                                   (containing bin, lib, etc)
 #   SQUISH_SERVER_EXECUTABLE        The squishserver executable
 #   SQUISH_CLIENT_EXECUTABLE        The squishrunner executable
 #
@@ -47,21 +48,26 @@
 #
 # The arguments have the following meaning:
 #
-# ::
-#
-#    cmakeTestName: this will be used as the first argument for add_test()
-#    AUT targetName: the name of the cmake target which will be used as AUT, i.e. the
-#                    executable which will be tested.
-#    SUITE suiteName: this is either the full path to the squish suite, or just the
-#                     last directory of the suite, i.e. the suite name. In this case
-#                     the CMakeLists.txt which calls squish_add_test() must be located
-#                     in the parent directory of the suite directory.
-#    TEST squishTestName: the name of the squish test, i.e. the name of the subdirectory
-#                         of the test inside the suite directory.
-#    SETTINGSGROUP group: if specified, the given settings group will be used for executing the test.
-#                         If not specified, the groupname will be "CTest_<username>"
-#    PRE_COMMAND command:  if specified, the given command will be executed before starting the squish test.
-#    POST_COMMAND command: same as PRE_COMMAND, but after the squish test has been executed.
+# ``cmakeTestName``
+#   this will be used as the first argument for add_test()
+# ``AUT targetName``
+#   the name of the cmake target which will be used as AUT, i.e. the
+#   executable which will be tested.
+# ``SUITE suiteName``
+#   this is either the full path to the squish suite, or just the
+#   last directory of the suite, i.e. the suite name. In this case
+#   the CMakeLists.txt which calls squish_add_test() must be located
+#   in the parent directory of the suite directory.
+# ``TEST squishTestName``
+#   the name of the squish test, i.e. the name of the subdirectory
+#   of the test inside the suite directory.
+# ``SETTINGSGROUP group``
+#   if specified, the given settings group will be used for executing the test.
+#   If not specified, the groupname will be "CTest_<username>"
+# ``PRE_COMMAND command``
+#   if specified, the given command will be executed before starting the squish test.
+# ``POST_COMMAND command``
+#   same as PRE_COMMAND, but after the squish test has been executed.
 #
 #
 #
@@ -70,7 +76,12 @@
 #    enable_testing()
 #    find_package(Squish 4.0)
 #    if (SQUISH_FOUND)
-#       squish_v4_add_test(myTestName AUT myApp SUITE ${CMAKE_SOURCE_DIR}/tests/mySuite TEST someSquishTest SETTINGSGROUP myGroup )
+#       squish_v4_add_test(myTestName
+#         AUT myApp
+#         SUITE ${CMAKE_SOURCE_DIR}/tests/mySuite
+#         TEST someSquishTest
+#         SETTINGSGROUP myGroup
+#         )
 #    endif ()
 #
 #
@@ -201,7 +212,7 @@
 endif()
 
 # record if Squish was found
-include(FindPackageHandleStandardArgs)
+include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 find_package_handle_standard_args(Squish  REQUIRED_VARS  SQUISH_INSTALL_DIR SQUISH_CLIENT_EXECUTABLE SQUISH_SERVER_EXECUTABLE
                                           VERSION_VAR  SQUISH_VERSION )
 
diff --git a/Modules/FindThreads.cmake b/Modules/FindThreads.cmake
index 6050dcd..a0bc4d1 100644
--- a/Modules/FindThreads.cmake
+++ b/Modules/FindThreads.cmake
@@ -14,14 +14,32 @@
 #   CMAKE_USE_PTHREADS_INIT    - are we using pthreads
 #   CMAKE_HP_PTHREADS_INIT     - are we using hp pthreads
 #
+# The following import target is created
+#
+# ::
+#
+#   Threads::Threads
+#
 # For systems with multiple thread libraries, caller can set
 #
 # ::
 #
 #   CMAKE_THREAD_PREFER_PTHREAD
+#
+# If the use of the -pthread compiler and linker flag is prefered then the
+# caller can set
+#
+# ::
+#
+#   THREADS_PREFER_PTHREAD_FLAG
+#
+# Please note that the compiler flag can only be used with the imported
+# target. Use of both the imported target as well as this switch is highly
+# recommended for new code.
 
 #=============================================================================
 # Copyright 2002-2009 Kitware, Inc.
+# Copyright 2011-2014 Rolf Eike Beer <eike@sf-mail.de>
 #
 # Distributed under the OSI-approved BSD License (the "License");
 # see accompanying file Copyright.txt for details.
@@ -45,6 +63,58 @@
   CHECK_INCLUDE_FILES("sys/types.h;sys/prctl.h"  CMAKE_HAVE_SPROC_H)
 endif()
 
+# Internal helper macro.
+# Do NOT even think about using it outside of this file!
+macro(_check_threads_lib LIBNAME FUNCNAME VARNAME)
+  if(NOT Threads_FOUND)
+     CHECK_LIBRARY_EXISTS(${LIBNAME} ${FUNCNAME} "" ${VARNAME})
+     if(${VARNAME})
+       set(CMAKE_THREAD_LIBS_INIT "-l${LIBNAME}")
+       set(CMAKE_HAVE_THREADS_LIBRARY 1)
+       set(Threads_FOUND TRUE)
+     endif()
+  endif ()
+endmacro()
+
+# Internal helper macro.
+# Do NOT even think about using it outside of this file!
+macro(_check_pthreads_flag)
+  if(NOT Threads_FOUND)
+    # If we did not found -lpthread, -lpthread, or -lthread, look for -pthread
+    if(NOT DEFINED THREADS_HAVE_PTHREAD_ARG)
+      message(STATUS "Check if compiler accepts -pthread")
+      try_run(THREADS_PTHREAD_ARG THREADS_HAVE_PTHREAD_ARG
+        ${CMAKE_BINARY_DIR}
+        ${CMAKE_CURRENT_LIST_DIR}/CheckForPthreads.c
+        CMAKE_FLAGS -DLINK_LIBRARIES:STRING=-pthread
+        COMPILE_OUTPUT_VARIABLE OUTPUT)
+
+      if(THREADS_HAVE_PTHREAD_ARG)
+        if(THREADS_PTHREAD_ARG STREQUAL "2")
+          set(Threads_FOUND TRUE)
+          message(STATUS "Check if compiler accepts -pthread - yes")
+        else()
+          message(STATUS "Check if compiler accepts -pthread - no")
+          file(APPEND
+            ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log
+            "Determining if compiler accepts -pthread returned ${THREADS_PTHREAD_ARG} instead of 2. The compiler had the following output:\n${OUTPUT}\n\n")
+        endif()
+      else()
+        message(STATUS "Check if compiler accepts -pthread - no")
+        file(APPEND
+          ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log
+          "Determining if compiler accepts -pthread failed with the following output:\n${OUTPUT}\n\n")
+      endif()
+
+    endif()
+
+    if(THREADS_HAVE_PTHREAD_ARG)
+      set(Threads_FOUND TRUE)
+      set(CMAKE_THREAD_LIBS_INIT "-pthread")
+    endif()
+  endif()
+endmacro()
+
 if(CMAKE_HAVE_SPROC_H AND NOT CMAKE_THREAD_PREFER_PTHREAD)
   # We have sproc
   set(CMAKE_USE_SPROC_INIT 1)
@@ -67,69 +137,23 @@
         set(Threads_FOUND TRUE)
       else()
 
-        # Do we have -lpthreads
-        CHECK_LIBRARY_EXISTS(pthreads pthread_create "" CMAKE_HAVE_PTHREADS_CREATE)
-        if(CMAKE_HAVE_PTHREADS_CREATE)
-          set(CMAKE_THREAD_LIBS_INIT "-lpthreads")
-          set(CMAKE_HAVE_THREADS_LIBRARY 1)
-          set(Threads_FOUND TRUE)
-        else()
+        # Check for -pthread first if enabled. This is the recommended
+        # way, but not backwards compatible as one must also pass -pthread
+        # as compiler flag then.
+        if (THREADS_PREFER_PTHREAD_FLAG)
+           _check_pthreads_flag()
+        endif ()
 
-          # Ok, how about -lpthread
-          CHECK_LIBRARY_EXISTS(pthread pthread_create "" CMAKE_HAVE_PTHREAD_CREATE)
-          if(CMAKE_HAVE_PTHREAD_CREATE)
-            set(CMAKE_THREAD_LIBS_INIT "-lpthread")
-            set(CMAKE_HAVE_THREADS_LIBRARY 1)
-            set(Threads_FOUND TRUE)
-
-          elseif(CMAKE_SYSTEM_NAME MATCHES "SunOS")
+        _check_threads_lib(pthreads pthread_create CMAKE_HAVE_PTHREADS_CREATE)
+        _check_threads_lib(pthread  pthread_create CMAKE_HAVE_PTHREAD_CREATE)
+        if(CMAKE_SYSTEM_NAME MATCHES "SunOS")
             # On sun also check for -lthread
-            CHECK_LIBRARY_EXISTS(thread thr_create "" CMAKE_HAVE_THR_CREATE)
-            if(CMAKE_HAVE_THR_CREATE)
-              set(CMAKE_THREAD_LIBS_INIT "-lthread")
-              set(CMAKE_HAVE_THREADS_LIBRARY 1)
-              set(Threads_FOUND TRUE)
-            endif()
-          endif()
+            _check_threads_lib(thread thr_create CMAKE_HAVE_THR_CREATE)
         endif()
       endif()
     endif()
 
-    if(NOT CMAKE_HAVE_THREADS_LIBRARY)
-      # If we did not found -lpthread, -lpthread, or -lthread, look for -pthread
-      if("x${THREADS_HAVE_PTHREAD_ARG}" STREQUAL "x")
-        message(STATUS "Check if compiler accepts -pthread")
-        try_run(THREADS_PTHREAD_ARG THREADS_HAVE_PTHREAD_ARG
-          ${CMAKE_BINARY_DIR}
-          ${CMAKE_ROOT}/Modules/CheckForPthreads.c
-          CMAKE_FLAGS -DLINK_LIBRARIES:STRING=-pthread
-          COMPILE_OUTPUT_VARIABLE OUTPUT)
-
-        if(THREADS_HAVE_PTHREAD_ARG)
-          if(THREADS_PTHREAD_ARG STREQUAL "2")
-            set(Threads_FOUND TRUE)
-            message(STATUS "Check if compiler accepts -pthread - yes")
-          else()
-            message(STATUS "Check if compiler accepts -pthread - no")
-            file(APPEND
-              ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log
-              "Determining if compiler accepts -pthread returned ${THREADS_PTHREAD_ARG} instead of 2. The compiler had the following output:\n${OUTPUT}\n\n")
-          endif()
-        else()
-          message(STATUS "Check if compiler accepts -pthread - no")
-          file(APPEND
-            ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log
-            "Determining if compiler accepts -pthread failed with the following output:\n${OUTPUT}\n\n")
-        endif()
-
-      endif()
-
-      if(THREADS_HAVE_PTHREAD_ARG)
-        set(Threads_FOUND TRUE)
-        set(CMAKE_THREAD_LIBS_INIT "-pthread")
-      endif()
-
-    endif()
+    _check_pthreads_flag()
   endif()
 endif()
 
@@ -178,3 +202,15 @@
 set(CMAKE_REQUIRED_QUIET ${CMAKE_REQUIRED_QUIET_SAVE})
 include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
 FIND_PACKAGE_HANDLE_STANDARD_ARGS(Threads DEFAULT_MSG Threads_FOUND)
+
+if(THREADS_FOUND AND NOT TARGET Threads::Threads)
+  add_library(Threads::Threads INTERFACE IMPORTED)
+
+  if(THREADS_HAVE_PTHREAD_ARG)
+    set_property(TARGET Threads::Threads PROPERTY INTERFACE_COMPILE_OPTIONS "-pthread")
+  endif()
+
+  if(CMAKE_THREAD_LIBS_INIT)
+    set_property(TARGET Threads::Threads PROPERTY INTERFACE_LINK_LIBRARIES "${CMAKE_THREAD_LIBS_INIT}")
+  endif()
+endif()
diff --git a/Modules/FindVTK.cmake b/Modules/FindVTK.cmake
deleted file mode 100644
index bcc7f87..0000000
--- a/Modules/FindVTK.cmake
+++ /dev/null
@@ -1,156 +0,0 @@
-#.rst:
-# FindVTK
-# -------
-#
-# Find a VTK installation or build tree.
-#
-# The following variables are set if VTK is found.  If VTK is not found,
-# VTK_FOUND is set to false.
-#
-# ::
-#
-#   VTK_FOUND         - Set to true when VTK is found.
-#   VTK_USE_FILE      - CMake file to use VTK.
-#   VTK_MAJOR_VERSION - The VTK major version number.
-#   VTK_MINOR_VERSION - The VTK minor version number
-#                        (odd non-release).
-#   VTK_BUILD_VERSION - The VTK patch level
-#                        (meaningless for odd minor).
-#   VTK_INCLUDE_DIRS  - Include directories for VTK
-#   VTK_LIBRARY_DIRS  - Link directories for VTK libraries
-#   VTK_KITS          - List of VTK kits, in CAPS
-#                       (COMMON,IO,) etc.
-#   VTK_LANGUAGES     - List of wrapped languages, in CAPS
-#                       (TCL, PYHTON,) etc.
-#
-# The following cache entries must be set by the user to locate VTK:
-#
-# ::
-#
-#   VTK_DIR  - The directory containing VTKConfig.cmake.
-#              This is either the root of the build tree,
-#              or the lib/vtk directory.  This is the
-#              only cache entry.
-#
-# The following variables are set for backward compatibility and should
-# not be used in new code:
-#
-# ::
-#
-#   USE_VTK_FILE - The full path to the UseVTK.cmake file.
-#                  This is provided for backward
-#                  compatibility.  Use VTK_USE_FILE
-#                  instead.
-
-#=============================================================================
-# Copyright 2001-2009 Kitware, Inc.
-#
-# Distributed under the OSI-approved BSD License (the "License");
-# see accompanying file Copyright.txt for details.
-#
-# This software is distributed WITHOUT ANY WARRANTY; without even the
-# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-# See the License for more information.
-#=============================================================================
-# (To distribute this file outside of CMake, substitute the full
-#  License text for the above reference.)
-
-# Assume not found.
-set(VTK_FOUND 0)
-
-# VTK 4.0 did not provide VTKConfig.cmake.
-if("${VTK_FIND_VERSION}" VERSION_LESS 4.1)
-  set(_VTK_40_ALLOW 1)
-  if(VTK_FIND_VERSION)
-    set(_VTK_40_ONLY 1)
-  endif()
-endif()
-
-# Construct consistent error messages for use below.
-set(VTK_DIR_DESCRIPTION "directory containing VTKConfig.cmake.  This is either the root of the build tree, or PREFIX/lib/vtk for an installation.")
-if(_VTK_40_ALLOW)
-  set(VTK_DIR_DESCRIPTION "${VTK_DIR_DESCRIPTION}  For VTK 4.0, this is the location of UseVTK.cmake.  This is either the root of the build tree or PREFIX/include/vtk for an installation.")
-endif()
-set(VTK_DIR_MESSAGE "VTK not found.  Set the VTK_DIR cmake cache entry to the ${VTK_DIR_DESCRIPTION}")
-
-# Check whether VTK 4.0 has already been found.
-if(_VTK_40_ALLOW AND VTK_DIR)
-  if(EXISTS ${VTK_DIR}/UseVTK.cmake AND NOT EXISTS ${VTK_DIR}/VTKConfig.cmake)
-    set(VTK_FOUND 1)
-    include(${CMAKE_CURRENT_LIST_DIR}/UseVTKConfig40.cmake) # No VTKConfig; load VTK 4.0 settings.
-  endif()
-endif()
-
-# Use the Config mode of the find_package() command to find VTKConfig.
-# If this succeeds (possibly because VTK_DIR is already set), the
-# command will have already loaded VTKConfig.cmake and set VTK_FOUND.
-if(NOT _VTK_40_ONLY AND NOT VTK_FOUND)
-  find_package(VTK QUIET NO_MODULE)
-endif()
-
-# Special search for VTK 4.0.
-if(_VTK_40_ALLOW AND NOT VTK_DIR)
-  # Old scripts may set these directories in the CMakeCache.txt file.
-  # They can tell us where to find VTKConfig.cmake.
-  set(VTK_DIR_SEARCH_LEGACY "")
-  if(VTK_BINARY_PATH AND USE_BUILT_VTK)
-    set(VTK_DIR_SEARCH_LEGACY ${VTK_DIR_SEARCH_LEGACY} ${VTK_BINARY_PATH})
-  endif()
-  if(VTK_INSTALL_PATH AND USE_INSTALLED_VTK)
-    set(VTK_DIR_SEARCH_LEGACY ${VTK_DIR_SEARCH_LEGACY}
-        ${VTK_INSTALL_PATH}/lib/vtk)
-  endif()
-
-  # Look for UseVTK.cmake in build trees or under <prefix>/include/vtk.
-  find_path(VTK_DIR
-    NAMES UseVTK.cmake
-    PATH_SUFFIXES vtk-4.0 vtk
-    HINTS ENV VTK_DIR
-
-    PATHS
-
-    # Support legacy cache files.
-    ${VTK_DIR_SEARCH_LEGACY}
-
-    # Read from the CMakeSetup registry entries.  It is likely that
-    # VTK will have been recently built.
-    [HKEY_CURRENT_USER\\Software\\Kitware\\CMakeSetup\\Settings\\StartPath;WhereBuild1]
-    [HKEY_CURRENT_USER\\Software\\Kitware\\CMakeSetup\\Settings\\StartPath;WhereBuild2]
-    [HKEY_CURRENT_USER\\Software\\Kitware\\CMakeSetup\\Settings\\StartPath;WhereBuild3]
-    [HKEY_CURRENT_USER\\Software\\Kitware\\CMakeSetup\\Settings\\StartPath;WhereBuild4]
-    [HKEY_CURRENT_USER\\Software\\Kitware\\CMakeSetup\\Settings\\StartPath;WhereBuild5]
-    [HKEY_CURRENT_USER\\Software\\Kitware\\CMakeSetup\\Settings\\StartPath;WhereBuild6]
-    [HKEY_CURRENT_USER\\Software\\Kitware\\CMakeSetup\\Settings\\StartPath;WhereBuild7]
-    [HKEY_CURRENT_USER\\Software\\Kitware\\CMakeSetup\\Settings\\StartPath;WhereBuild8]
-    [HKEY_CURRENT_USER\\Software\\Kitware\\CMakeSetup\\Settings\\StartPath;WhereBuild9]
-    [HKEY_CURRENT_USER\\Software\\Kitware\\CMakeSetup\\Settings\\StartPath;WhereBuild10]
-
-    # Help the user find it if we cannot.
-    DOC "The ${VTK_DIR_DESCRIPTION}"
-    )
-
-  if(VTK_DIR)
-    if(EXISTS ${VTK_DIR}/UseVTK.cmake AND NOT EXISTS ${VTK_DIR}/VTKConfig.cmake)
-      set(VTK_FOUND 1)
-      include(${CMAKE_CURRENT_LIST_DIR}/UseVTKConfig40.cmake) # No VTKConfig; load VTK 4.0 settings.
-    else()
-      # We found the wrong version.  Pretend we did not find it.
-      set(VTK_DIR "VTK_DIR-NOTFOUND" CACHE PATH "The ${VTK_DIR_DESCRIPTION}" FORCE)
-    endif()
-  endif()
-endif()
-
-#-----------------------------------------------------------------------------
-if(VTK_FOUND)
-  # Set USE_VTK_FILE for backward-compatibility.
-  set(USE_VTK_FILE ${VTK_USE_FILE})
-else()
-  # VTK not found, explain to the user how to specify its location.
-  if(VTK_FIND_REQUIRED)
-    message(FATAL_ERROR ${VTK_DIR_MESSAGE})
-  else()
-    if(NOT VTK_FIND_QUIETLY)
-      message(STATUS ${VTK_DIR_MESSAGE})
-    endif()
-  endif()
-endif()
diff --git a/Modules/FindX11.cmake b/Modules/FindX11.cmake
index 3a31cf0..90c1499 100644
--- a/Modules/FindX11.cmake
+++ b/Modules/FindX11.cmake
@@ -4,7 +4,7 @@
 #
 # Find X11 installation
 #
-# Try to find X11 on UNIX systems.  The following values are defined
+# Try to find X11 on UNIX systems. The following values are defined
 #
 # ::
 #
@@ -12,47 +12,44 @@
 #   X11_INCLUDE_DIR  - include directories to use X11
 #   X11_LIBRARIES    - link against these to use X11
 #
-#
-#
-# and also the following more fine grained variables: Include paths:
-# X11_ICE_INCLUDE_PATH, X11_ICE_LIB, X11_ICE_FOUND
+# and also the following more fine grained variables:
 #
 # ::
 #
-#                 X11_SM_INCLUDE_PATH,           X11_SM_LIB,         X11_SM_FOUND
-#                 X11_X11_INCLUDE_PATH,          X11_X11_LIB
-#                 X11_Xaccessrules_INCLUDE_PATH,                     X11_Xaccess_FOUND
-#                 X11_Xaccessstr_INCLUDE_PATH,                       X11_Xaccess_FOUND
-#                 X11_Xau_INCLUDE_PATH,          X11_Xau_LIB,        X11_Xau_FOUND
-#                 X11_Xcomposite_INCLUDE_PATH,   X11_Xcomposite_LIB, X11_Xcomposite_FOUND
-#                 X11_Xcursor_INCLUDE_PATH,      X11_Xcursor_LIB,    X11_Xcursor_FOUND
-#                 X11_Xdamage_INCLUDE_PATH,      X11_Xdamage_LIB,    X11_Xdamage_FOUND
-#                 X11_Xdmcp_INCLUDE_PATH,        X11_Xdmcp_LIB,      X11_Xdmcp_FOUND
-#                                                X11_Xext_LIB,       X11_Xext_FOUND
-#                 X11_dpms_INCLUDE_PATH,         (in X11_Xext_LIB),  X11_dpms_FOUND
-#                 X11_XShm_INCLUDE_PATH,         (in X11_Xext_LIB),  X11_XShm_FOUND
-#                 X11_Xshape_INCLUDE_PATH,       (in X11_Xext_LIB),  X11_Xshape_FOUND
-#                 X11_xf86misc_INCLUDE_PATH,     X11_Xxf86misc_LIB,  X11_xf86misc_FOUND
-#                 X11_xf86vmode_INCLUDE_PATH,    X11_Xxf86vm_LIB     X11_xf86vmode_FOUND
-#                 X11_Xfixes_INCLUDE_PATH,       X11_Xfixes_LIB,     X11_Xfixes_FOUND
-#                 X11_Xft_INCLUDE_PATH,          X11_Xft_LIB,        X11_Xft_FOUND
-#                 X11_Xi_INCLUDE_PATH,           X11_Xi_LIB,         X11_Xi_FOUND
-#                 X11_Xinerama_INCLUDE_PATH,     X11_Xinerama_LIB,   X11_Xinerama_FOUND
-#                 X11_Xinput_INCLUDE_PATH,       X11_Xinput_LIB,     X11_Xinput_FOUND
-#                 X11_Xkb_INCLUDE_PATH,                              X11_Xkb_FOUND
-#                 X11_Xkblib_INCLUDE_PATH,                           X11_Xkb_FOUND
-#                 X11_Xkbfile_INCLUDE_PATH,      X11_Xkbfile_LIB,    X11_Xkbfile_FOUND
-#                 X11_Xmu_INCLUDE_PATH,          X11_Xmu_LIB,        X11_Xmu_FOUND
-#                 X11_Xpm_INCLUDE_PATH,          X11_Xpm_LIB,        X11_Xpm_FOUND
-#                 X11_XTest_INCLUDE_PATH,        X11_XTest_LIB,      X11_XTest_FOUND
-#                 X11_Xrandr_INCLUDE_PATH,       X11_Xrandr_LIB,     X11_Xrandr_FOUND
-#                 X11_Xrender_INCLUDE_PATH,      X11_Xrender_LIB,    X11_Xrender_FOUND
-#                 X11_Xscreensaver_INCLUDE_PATH, X11_Xscreensaver_LIB, X11_Xscreensaver_FOUND
-#                 X11_Xt_INCLUDE_PATH,           X11_Xt_LIB,         X11_Xt_FOUND
-#                 X11_Xutil_INCLUDE_PATH,                            X11_Xutil_FOUND
-#                 X11_Xv_INCLUDE_PATH,           X11_Xv_LIB,         X11_Xv_FOUND
-#                 X11_XSync_INCLUDE_PATH,        (in X11_Xext_LIB),  X11_XSync_FOUND
-
+#   X11_ICE_INCLUDE_PATH,          X11_ICE_LIB,        X11_ICE_FOUND
+#   X11_SM_INCLUDE_PATH,           X11_SM_LIB,         X11_SM_FOUND
+#   X11_X11_INCLUDE_PATH,          X11_X11_LIB
+#   X11_Xaccessrules_INCLUDE_PATH,                     X11_Xaccess_FOUND
+#   X11_Xaccessstr_INCLUDE_PATH,                       X11_Xaccess_FOUND
+#   X11_Xau_INCLUDE_PATH,          X11_Xau_LIB,        X11_Xau_FOUND
+#   X11_Xcomposite_INCLUDE_PATH,   X11_Xcomposite_LIB, X11_Xcomposite_FOUND
+#   X11_Xcursor_INCLUDE_PATH,      X11_Xcursor_LIB,    X11_Xcursor_FOUND
+#   X11_Xdamage_INCLUDE_PATH,      X11_Xdamage_LIB,    X11_Xdamage_FOUND
+#   X11_Xdmcp_INCLUDE_PATH,        X11_Xdmcp_LIB,      X11_Xdmcp_FOUND
+#   X11_Xext_LIB,       X11_Xext_FOUND
+#   X11_dpms_INCLUDE_PATH,         (in X11_Xext_LIB),  X11_dpms_FOUND
+#   X11_XShm_INCLUDE_PATH,         (in X11_Xext_LIB),  X11_XShm_FOUND
+#   X11_Xshape_INCLUDE_PATH,       (in X11_Xext_LIB),  X11_Xshape_FOUND
+#   X11_xf86misc_INCLUDE_PATH,     X11_Xxf86misc_LIB,  X11_xf86misc_FOUND
+#   X11_xf86vmode_INCLUDE_PATH,    X11_Xxf86vm_LIB     X11_xf86vmode_FOUND
+#   X11_Xfixes_INCLUDE_PATH,       X11_Xfixes_LIB,     X11_Xfixes_FOUND
+#   X11_Xft_INCLUDE_PATH,          X11_Xft_LIB,        X11_Xft_FOUND
+#   X11_Xi_INCLUDE_PATH,           X11_Xi_LIB,         X11_Xi_FOUND
+#   X11_Xinerama_INCLUDE_PATH,     X11_Xinerama_LIB,   X11_Xinerama_FOUND
+#   X11_Xinput_INCLUDE_PATH,       X11_Xinput_LIB,     X11_Xinput_FOUND
+#   X11_Xkb_INCLUDE_PATH,                              X11_Xkb_FOUND
+#   X11_Xkblib_INCLUDE_PATH,                           X11_Xkb_FOUND
+#   X11_Xkbfile_INCLUDE_PATH,      X11_Xkbfile_LIB,    X11_Xkbfile_FOUND
+#   X11_Xmu_INCLUDE_PATH,          X11_Xmu_LIB,        X11_Xmu_FOUND
+#   X11_Xpm_INCLUDE_PATH,          X11_Xpm_LIB,        X11_Xpm_FOUND
+#   X11_XTest_INCLUDE_PATH,        X11_XTest_LIB,      X11_XTest_FOUND
+#   X11_Xrandr_INCLUDE_PATH,       X11_Xrandr_LIB,     X11_Xrandr_FOUND
+#   X11_Xrender_INCLUDE_PATH,      X11_Xrender_LIB,    X11_Xrender_FOUND
+#   X11_Xscreensaver_INCLUDE_PATH, X11_Xscreensaver_LIB, X11_Xscreensaver_FOUND
+#   X11_Xt_INCLUDE_PATH,           X11_Xt_LIB,         X11_Xt_FOUND
+#   X11_Xutil_INCLUDE_PATH,                            X11_Xutil_FOUND
+#   X11_Xv_INCLUDE_PATH,           X11_Xv_LIB,         X11_Xv_FOUND
+#   X11_XSync_INCLUDE_PATH,        (in X11_Xext_LIB),  X11_XSync_FOUND
 
 #=============================================================================
 # Copyright 2001-2009 Kitware, Inc.
diff --git a/Modules/FindXerces.cmake b/Modules/FindXerces.cmake
new file mode 100644
index 0000000..6c6007a
--- /dev/null
+++ b/Modules/FindXerces.cmake
@@ -0,0 +1,85 @@
+#.rst:
+# FindXerces
+# ----------
+#
+# Find the Apache Xerces-C++ validating XML parser headers and libraries.
+#
+# This module reports information about the Xerces installation in
+# several variables.  General variables::
+#
+#   Xerces_FOUND - true if the Xerces headers and libraries were found
+#   Xerces_VERSION - Xerces release version
+#   Xerces_INCLUDE_DIRS - the directory containing the Xerces headers
+#   Xerces_LIBRARIES - Xerces libraries to be linked
+#
+# The following cache variables may also be set::
+#
+#   Xerces_INCLUDE_DIR - the directory containing the Xerces headers
+#   Xerces_LIBRARY - the Xerces library
+
+# Written by Roger Leigh <rleigh@codelibre.net>
+
+#=============================================================================
+# Copyright 2014 University of Dundee
+#
+# Distributed under the OSI-approved BSD License (the "License");
+# see accompanying file Copyright.txt for details.
+#
+# This software is distributed WITHOUT ANY WARRANTY; without even the
+# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+# See the License for more information.
+#=============================================================================
+# (To distribute this file outside of CMake, substitute the full
+#  License text for the above reference.)
+
+function(_Xerces_GET_VERSION  version_hdr)
+    file(STRINGS ${version_hdr} _contents REGEX "^[ \t]*#define XERCES_VERSION_.*")
+    if(_contents)
+        string(REGEX REPLACE ".*#define XERCES_VERSION_MAJOR[ \t]+([0-9]+).*" "\\1" Xerces_MAJOR "${_contents}")
+        string(REGEX REPLACE ".*#define XERCES_VERSION_MINOR[ \t]+([0-9]+).*" "\\1" Xerces_MINOR "${_contents}")
+        string(REGEX REPLACE ".*#define XERCES_VERSION_REVISION[ \t]+([0-9]+).*" "\\1" Xerces_PATCH "${_contents}")
+
+        if(NOT Xerces_MAJOR MATCHES "^[0-9]+$")
+            message(FATAL_ERROR "Version parsing failed for XERCES_VERSION_MAJOR!")
+        endif()
+        if(NOT Xerces_MINOR MATCHES "^[0-9]+$")
+            message(FATAL_ERROR "Version parsing failed for XERCES_VERSION_MINOR!")
+        endif()
+        if(NOT Xerces_PATCH MATCHES "^[0-9]+$")
+            message(FATAL_ERROR "Version parsing failed for XERCES_VERSION_REVISION!")
+        endif()
+
+        set(Xerces_VERSION "${Xerces_MAJOR}.${Xerces_MINOR}.${Xerces_PATCH}" PARENT_SCOPE)
+    else()
+        message(FATAL_ERROR "Include file ${version_hdr} does not exist or does not contain expected version information")
+    endif()
+endfunction()
+
+# Find include directory
+find_path(Xerces_INCLUDE_DIR
+          NAMES "xercesc/util/PlatformUtils.hpp"
+          DOC "Xerces-C++ include directory")
+mark_as_advanced(Xerces_INCLUDE_DIR)
+
+# Find all Xerces libraries
+find_library(Xerces_LIBRARY "xerces-c"
+  DOC "Xerces-C++ libraries")
+mark_as_advanced(Xerces_LIBRARY)
+
+if(Xerces_INCLUDE_DIR)
+  _Xerces_GET_VERSION("${Xerces_INCLUDE_DIR}/xercesc/util/XercesVersion.hpp")
+endif()
+
+include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
+FIND_PACKAGE_HANDLE_STANDARD_ARGS(Xerces
+                                  FOUND_VAR Xerces_FOUND
+                                  REQUIRED_VARS Xerces_LIBRARY
+                                                Xerces_INCLUDE_DIR
+                                                Xerces_VERSION
+                                  VERSION_VAR Xerces_VERSION
+                                  FAIL_MESSAGE "Failed to find Xerces")
+
+if(Xerces_FOUND)
+  set(Xerces_INCLUDE_DIRS "${Xerces_INCLUDE_DIR}")
+  set(Xerces_LIBRARIES "${Xerces_LIBRARY}")
+endif()
diff --git a/Modules/FindZLIB.cmake b/Modules/FindZLIB.cmake
index 8cc382c..d4a27d5 100644
--- a/Modules/FindZLIB.cmake
+++ b/Modules/FindZLIB.cmake
@@ -2,9 +2,18 @@
 # FindZLIB
 # --------
 #
-# Find zlib
+# Find the native ZLIB includes and library.
 #
-# Find the native ZLIB includes and library.  Once done this will define
+# IMPORTED Targets
+# ^^^^^^^^^^^^^^^^
+#
+# This module defines :prop_tgt:`IMPORTED` target ``ZLIB::ZLIB``, if
+# ZLIB has been found.
+#
+# Result Variables
+# ^^^^^^^^^^^^^^^^
+#
+# This module defines the following variables:
 #
 # ::
 #
@@ -12,8 +21,6 @@
 #   ZLIB_LIBRARIES      - List of libraries when using zlib.
 #   ZLIB_FOUND          - True if zlib found.
 #
-#
-#
 # ::
 #
 #   ZLIB_VERSION_STRING - The version of zlib found (x.y.z)
@@ -22,7 +29,8 @@
 #   ZLIB_VERSION_PATCH  - The patch version of zlib
 #   ZLIB_VERSION_TWEAK  - The tweak version of zlib
 #
-#
+# Backward Compatibility
+# ^^^^^^^^^^^^^^^^^^^^^^
 #
 # The following variable are provided for backward compatibility
 #
@@ -32,9 +40,10 @@
 #   ZLIB_MINOR_VERSION  - The minor version of zlib
 #   ZLIB_PATCH_VERSION  - The patch version of zlib
 #
+# Hints
+# ^^^^^
 #
-#
-# An includer may set ZLIB_ROOT to a zlib installation root to tell this
+# A user may set ``ZLIB_ROOT`` to a zlib installation root to tell this
 # module where to look.
 
 #=============================================================================
@@ -104,5 +113,11 @@
 if(ZLIB_FOUND)
     set(ZLIB_INCLUDE_DIRS ${ZLIB_INCLUDE_DIR})
     set(ZLIB_LIBRARIES ${ZLIB_LIBRARY})
-endif()
 
+    if(NOT TARGET ZLIB::ZLIB)
+      add_library(ZLIB::ZLIB UNKNOWN IMPORTED)
+      set_target_properties(ZLIB::ZLIB PROPERTIES
+        IMPORTED_LOCATION "${ZLIB_LIBRARY}"
+        INTERFACE_INCLUDE_DIRECTORIES "${ZLIB_INCLUDE_DIRS}")
+    endif()
+endif()
diff --git a/Modules/FindwxWidgets.cmake b/Modules/FindwxWidgets.cmake
index 45596a0..7ef06a8 100644
--- a/Modules/FindwxWidgets.cmake
+++ b/Modules/FindwxWidgets.cmake
@@ -229,13 +229,12 @@
 endif()
 
 #=====================================================================
+# Determine whether unix or win32 paths should be used
 #=====================================================================
-if(WIN32 AND NOT CYGWIN AND NOT MSYS)
+if(WIN32 AND NOT CYGWIN AND NOT MSYS AND NOT CMAKE_CROSSCOMPILING)
   set(wxWidgets_FIND_STYLE "win32")
 else()
-  if(UNIX OR MSYS)
-    set(wxWidgets_FIND_STYLE "unix")
-  endif()
+  set(wxWidgets_FIND_STYLE "unix")
 endif()
 
 #=====================================================================
diff --git a/Modules/FortranCInterface/Detect.cmake b/Modules/FortranCInterface/Detect.cmake
index ceb1db4..bee7dae 100644
--- a/Modules/FortranCInterface/Detect.cmake
+++ b/Modules/FortranCInterface/Detect.cmake
@@ -67,7 +67,7 @@
 set(FortranCInterface_SYMBOLS)
 if(FortranCInterface_EXE)
   file(STRINGS "${FortranCInterface_EXE}" _info_strings
-    LIMIT_COUNT 8 REGEX "INFO:[^[]*\\[")
+    LIMIT_COUNT 8 REGEX "INFO:[A-Za-z0-9_]+\\[[^]]*\\]")
   foreach(info ${_info_strings})
     if("${info}" MATCHES "INFO:symbol\\[([^]]*)\\]")
       list(APPEND FortranCInterface_SYMBOLS ${CMAKE_MATCH_1})
diff --git a/Modules/GNUInstallDirs.cmake b/Modules/GNUInstallDirs.cmake
index eac553d..c61e7e9 100644
--- a/Modules/GNUInstallDirs.cmake
+++ b/Modules/GNUInstallDirs.cmake
@@ -6,36 +6,47 @@
 #
 # Provides install directory variables as defined for GNU software:
 #
-# ::
-#
 #   http://www.gnu.org/prep/standards/html_node/Directory-Variables.html
 #
 # Inclusion of this module defines the following variables:
 #
-# ::
-#
-#   CMAKE_INSTALL_<dir>      - destination for files of a given type
-#   CMAKE_INSTALL_FULL_<dir> - corresponding absolute path
+# ``CMAKE_INSTALL_<dir>``
+#   destination for files of a given type
+# ``CMAKE_INSTALL_FULL_<dir>``
+#   corresponding absolute path
 #
 # where <dir> is one of:
 #
-# ::
-#
-#   BINDIR           - user executables (bin)
-#   SBINDIR          - system admin executables (sbin)
-#   LIBEXECDIR       - program executables (libexec)
-#   SYSCONFDIR       - read-only single-machine data (etc)
-#   SHAREDSTATEDIR   - modifiable architecture-independent data (com)
-#   LOCALSTATEDIR    - modifiable single-machine data (var)
-#   LIBDIR           - object code libraries (lib or lib64 or lib/<multiarch-tuple> on Debian)
-#   INCLUDEDIR       - C header files (include)
-#   OLDINCLUDEDIR    - C header files for non-gcc (/usr/include)
-#   DATAROOTDIR      - read-only architecture-independent data root (share)
-#   DATADIR          - read-only architecture-independent data (DATAROOTDIR)
-#   INFODIR          - info documentation (DATAROOTDIR/info)
-#   LOCALEDIR        - locale-dependent data (DATAROOTDIR/locale)
-#   MANDIR           - man documentation (DATAROOTDIR/man)
-#   DOCDIR           - documentation root (DATAROOTDIR/doc/PROJECT_NAME)
+# ``BINDIR``
+#   user executables (bin)
+# ``SBINDIR``
+#   system admin executables (sbin)
+# ``LIBEXECDIR``
+#   program executables (libexec)
+# ``SYSCONFDIR``
+#   read-only single-machine data (etc)
+# ``SHAREDSTATEDIR``
+#   modifiable architecture-independent data (com)
+# ``LOCALSTATEDIR``
+#   modifiable single-machine data (var)
+# ``LIBDIR``
+#   object code libraries (lib or lib64 or lib/<multiarch-tuple> on Debian)
+# ``INCLUDEDIR``
+#   C header files (include)
+# ``OLDINCLUDEDIR``
+#   C header files for non-gcc (/usr/include)
+# ``DATAROOTDIR``
+#   read-only architecture-independent data root (share)
+# ``DATADIR``
+#   read-only architecture-independent data (DATAROOTDIR)
+# ``INFODIR``
+#   info documentation (DATAROOTDIR/info)
+# ``LOCALEDIR``
+#   locale-dependent data (DATAROOTDIR/locale)
+# ``MANDIR``
+#   man documentation (DATAROOTDIR/man)
+# ``DOCDIR``
+#   documentation root (DATAROOTDIR/doc/PROJECT_NAME)
 #
 # Each CMAKE_INSTALL_<dir> value may be passed to the DESTINATION
 # options of install() commands for the corresponding file type.  If the
@@ -198,7 +209,7 @@
     set(CMAKE_INSTALL_INFODIR "info")
   endif()
 
-  if(NOT CMAKE_INSTALL_MANDDIR)
+  if(NOT CMAKE_INSTALL_MANDIR)
     set(CMAKE_INSTALL_MANDIR "" CACHE PATH "man documentation (man)")
     set(CMAKE_INSTALL_MANDIR "man")
   endif()
@@ -208,7 +219,7 @@
     set(CMAKE_INSTALL_INFODIR "${CMAKE_INSTALL_DATAROOTDIR}/info")
   endif()
 
-  if(NOT CMAKE_INSTALL_MANDDIR)
+  if(NOT CMAKE_INSTALL_MANDIR)
     set(CMAKE_INSTALL_MANDIR "" CACHE PATH "man documentation (DATAROOTDIR/man)")
     set(CMAKE_INSTALL_MANDIR "${CMAKE_INSTALL_DATAROOTDIR}/man")
   endif()
diff --git a/Modules/GenerateExportHeader.cmake b/Modules/GenerateExportHeader.cmake
index f83f992..0c6256c 100644
--- a/Modules/GenerateExportHeader.cmake
+++ b/Modules/GenerateExportHeader.cmake
@@ -213,14 +213,13 @@
 
   # Exclude XL here because it misinterprets -fvisibility=hidden even though
   # the check_cxx_compiler_flag passes
-  # http://www.cdash.org/CDash/testDetails.php?test=109109951&build=1419259
   if(NOT GCC_TOO_OLD
       AND NOT _INTEL_TOO_OLD
       AND NOT WIN32
       AND NOT CYGWIN
-      AND NOT "${CMAKE_CXX_COMPILER_ID}" MATCHES XL
-      AND NOT "${CMAKE_CXX_COMPILER_ID}" MATCHES PGI
-      AND NOT "${CMAKE_CXX_COMPILER_ID}" MATCHES Watcom)
+      AND NOT CMAKE_CXX_COMPILER_ID MATCHES XL
+      AND NOT CMAKE_CXX_COMPILER_ID MATCHES PGI
+      AND NOT CMAKE_CXX_COMPILER_ID MATCHES Watcom)
     check_cxx_compiler_flag(-fvisibility=hidden COMPILER_HAS_HIDDEN_VISIBILITY)
     check_cxx_compiler_flag(-fvisibility-inlines-hidden
       COMPILER_HAS_HIDDEN_INLINE_VISIBILITY)
@@ -231,11 +230,11 @@
 endmacro()
 
 macro(_test_compiler_has_deprecated)
-  if("${CMAKE_CXX_COMPILER_ID}" MATCHES Borland
-      OR "${CMAKE_CXX_COMPILER_ID}" MATCHES HP
+  if(CMAKE_CXX_COMPILER_ID MATCHES Borland
+      OR CMAKE_CXX_COMPILER_ID MATCHES HP
       OR GCC_TOO_OLD
-      OR "${CMAKE_CXX_COMPILER_ID}" MATCHES PGI
-      OR "${CMAKE_CXX_COMPILER_ID}" MATCHES Watcom)
+      OR CMAKE_CXX_COMPILER_ID MATCHES PGI
+      OR CMAKE_CXX_COMPILER_ID MATCHES Watcom)
     set(COMPILER_HAS_DEPRECATED "" CACHE INTERNAL
       "Compiler support for a deprecated attribute")
   else()
@@ -364,6 +363,7 @@
   get_property(type TARGET ${TARGET_LIBRARY} PROPERTY TYPE)
   if(NOT ${type} STREQUAL "STATIC_LIBRARY"
       AND NOT ${type} STREQUAL "SHARED_LIBRARY"
+      AND NOT ${type} STREQUAL "OBJECT_LIBRARY"
       AND NOT ${type} STREQUAL "MODULE_LIBRARY")
     message(WARNING "This macro can only be used with libraries")
     return()
diff --git a/Modules/GetPrerequisites.cmake b/Modules/GetPrerequisites.cmake
index 05c2edb..9963517 100644
--- a/Modules/GetPrerequisites.cmake
+++ b/Modules/GetPrerequisites.cmake
@@ -41,7 +41,7 @@
 # ::
 #
 #   GET_PREREQUISITES(<target> <prerequisites_var> <exclude_system> <recurse>
-#                     <exepath> <dirs>)
+#                     <exepath> <dirs> [<rpaths>])
 #
 # Get the list of shared library files required by <target>.  The list
 # in the variable named <prerequisites_var> should be empty on first
@@ -113,7 +113,8 @@
 #
 # ::
 #
-#   GP_RESOLVE_ITEM(<context> <item> <exepath> <dirs> <resolved_item_var>)
+#   GP_RESOLVE_ITEM(<context> <item> <exepath> <dirs> <resolved_item_var>
+#                   [<rpaths>])
 #
 # Resolve an item into an existing full path file.
 #
@@ -122,7 +123,8 @@
 #
 # ::
 #
-#   GP_RESOLVED_FILE_TYPE(<original_file> <file> <exepath> <dirs> <type_var>)
+#   GP_RESOLVED_FILE_TYPE(<original_file> <file> <exepath> <dirs> <type_var>
+#                         [<rpaths>])
 #
 # Return the type of <file> with respect to <original_file>.  String
 # describing type of prerequisite is returned in variable named
@@ -321,6 +323,7 @@
 function(gp_resolve_item context item exepath dirs resolved_item_var)
   set(resolved 0)
   set(resolved_item "${item}")
+  set(rpaths "${ARGV5}")
 
   # Is it already resolved?
   #
@@ -329,7 +332,7 @@
   endif()
 
   if(NOT resolved)
-    if(item MATCHES "@executable_path")
+    if(item MATCHES "^@executable_path")
       #
       # @executable_path references are assumed relative to exepath
       #
@@ -347,7 +350,7 @@
   endif()
 
   if(NOT resolved)
-    if(item MATCHES "@loader_path")
+    if(item MATCHES "^@loader_path")
       #
       # @loader_path references are assumed relative to the
       # PATH of the given "context" (presumably another library)
@@ -367,7 +370,7 @@
   endif()
 
   if(NOT resolved)
-    if(item MATCHES "@rpath")
+    if(item MATCHES "^@rpath")
       #
       # @rpath references are relative to the paths built into the binaries with -rpath
       # We handle this case like we do for other Unixes
@@ -375,9 +378,9 @@
       string(REPLACE "@rpath/" "" norpath_item "${item}")
 
       set(ri "ri-NOTFOUND")
-      find_file(ri "${norpath_item}" ${exepath} ${dirs} NO_DEFAULT_PATH)
+      find_file(ri "${norpath_item}" ${exepath} ${dirs} ${rpaths} NO_DEFAULT_PATH)
       if(ri)
-        #message(STATUS "info: 'find_file' in exepath/dirs (${ri})")
+        #message(STATUS "info: 'find_file' in exepath/dirs/rpaths (${ri})")
         set(resolved 1)
         set(resolved_item "${ri}")
         set(ri "ri-NOTFOUND")
@@ -471,6 +474,7 @@
 
 
 function(gp_resolved_file_type original_file file exepath dirs type_var)
+  set(rpaths "${ARGV5}")
   #message(STATUS "**")
 
   if(NOT IS_ABSOLUTE "${original_file}")
@@ -489,7 +493,7 @@
 
   if(NOT is_embedded)
     if(NOT IS_ABSOLUTE "${file}")
-      gp_resolve_item("${original_file}" "${file}" "${exepath}" "${dirs}" resolved_file)
+      gp_resolve_item("${original_file}" "${file}" "${exepath}" "${dirs}" resolved_file "${rpaths}")
     endif()
 
     string(TOLOWER "${original_file}" original_lower)
@@ -612,6 +616,7 @@
 function(get_prerequisites target prerequisites_var exclude_system recurse exepath dirs)
   set(verbose 0)
   set(eol_char "E")
+  set(rpaths "${ARGV6}")
 
   if(NOT IS_ABSOLUTE "${target}")
     message("warning: target '${target}' is not absolute...")
@@ -834,7 +839,7 @@
 
     if(add_item AND ${exclude_system})
       set(type "")
-      gp_resolved_file_type("${target}" "${item}" "${exepath}" "${dirs}" type)
+      gp_resolved_file_type("${target}" "${item}" "${exepath}" "${dirs}" type "${rpaths}")
 
       if("${type}" STREQUAL "system")
         set(add_item 0)
@@ -855,7 +860,7 @@
         # that the analysis tools can simply accept it as input.
         #
         if(NOT list_length_before_append EQUAL list_length_after_append)
-          gp_resolve_item("${target}" "${item}" "${exepath}" "${dirs}" resolved_item)
+          gp_resolve_item("${target}" "${item}" "${exepath}" "${dirs}" resolved_item "${rpaths}")
           set(unseen_prereqs ${unseen_prereqs} "${resolved_item}")
         endif()
       endif()
@@ -874,7 +879,7 @@
   if(${recurse})
     set(more_inputs ${unseen_prereqs})
     foreach(input ${more_inputs})
-      get_prerequisites("${input}" ${prerequisites_var} ${exclude_system} ${recurse} "${exepath}" "${dirs}")
+      get_prerequisites("${input}" ${prerequisites_var} ${exclude_system} ${recurse} "${exepath}" "${dirs}" "${rpaths}")
     endforeach()
   endif()
 
diff --git a/Modules/InstallRequiredSystemLibraries.cmake b/Modules/InstallRequiredSystemLibraries.cmake
index 5c439e9..5afb517 100644
--- a/Modules/InstallRequiredSystemLibraries.cmake
+++ b/Modules/InstallRequiredSystemLibraries.cmake
@@ -19,6 +19,8 @@
 # libraries are installed when both debug and release are available.  If
 # CMAKE_INSTALL_MFC_LIBRARIES is set then the MFC run time libraries are
 # installed as well as the CRT run time libraries.  If
+# CMAKE_INSTALL_OPENMP_LIBRARIES is set then the OpenMP run time libraries
+# are installed as well.  If
 # CMAKE_INSTALL_SYSTEM_RUNTIME_DESTINATION is set then the libraries are
 # installed to that directory rather than the default.  If
 # CMAKE_INSTALL_SYSTEM_RUNTIME_LIBS_NO_WARNINGS is NOT set, then this
@@ -94,6 +96,8 @@
         "${MSVC80_CRT_DIR}/msvcp80.dll"
         "${MSVC80_CRT_DIR}/msvcr80.dll"
         )
+    else()
+      set(__install__libs)
     endif()
 
     if(CMAKE_INSTALL_DEBUG_LIBRARIES)
@@ -132,6 +136,8 @@
         "${MSVC90_CRT_DIR}/msvcp90.dll"
         "${MSVC90_CRT_DIR}/msvcr90.dll"
         )
+    else()
+      set(__install__libs)
     endif()
 
     if(CMAKE_INSTALL_DEBUG_LIBRARIES)
@@ -168,6 +174,8 @@
         "${MSVC${v}_CRT_DIR}/msvcp${v}0.dll"
         "${MSVC${v}_CRT_DIR}/msvcr${v}0.dll"
         )
+    else()
+      set(__install__libs)
     endif()
 
     if(CMAKE_INSTALL_DEBUG_LIBRARIES)
@@ -192,6 +200,10 @@
     MSVCRT_FILES_FOR_VERSION(12)
   endif()
 
+  if(MSVC14)
+    MSVCRT_FILES_FOR_VERSION(14)
+  endif()
+
   if(CMAKE_INSTALL_MFC_LIBRARIES)
     if(MSVC70)
       set(__install__libs ${__install__libs}
@@ -361,6 +373,44 @@
     if(MSVC12)
       MFC_FILES_FOR_VERSION(12)
     endif()
+
+    if(MSVC14)
+      MFC_FILES_FOR_VERSION(14)
+    endif()
+  endif()
+
+  # MSVC 8 was the first version with OpenMP
+  # Furthermore, there is no debug version of this
+  if(CMAKE_INSTALL_OPENMP_LIBRARIES)
+    macro(OPENMP_FILES_FOR_VERSION version_a version_b)
+      set(va "${version_a}")
+      set(vb "${version_b}")
+      set(MSVC${va}_OPENMP_DIR "${MSVC${va}_REDIST_DIR}/${CMAKE_MSVC_ARCH}/Microsoft.VC${vb}.OPENMP")
+
+      if(NOT CMAKE_INSTALL_DEBUG_LIBRARIES_ONLY)
+        set(__install__libs ${__install__libs}
+          "${MSVC${va}_OPENMP_DIR}/vcomp${vb}.dll")
+      endif()
+    endmacro()
+
+    if(MSVC80)
+      OPENMP_FILES_FOR_VERSION(80 80)
+    endif()
+    if(MSVC90)
+      OPENMP_FILES_FOR_VERSION(90 90)
+    endif()
+    if(MSVC10)
+      OPENMP_FILES_FOR_VERSION(10 100)
+    endif()
+    if(MSVC11)
+      OPENMP_FILES_FOR_VERSION(11 110)
+    endif()
+    if(MSVC12)
+      OPENMP_FILES_FOR_VERSION(12 120)
+    endif()
+    if(MSVC14)
+      OPENMP_FILES_FOR_VERSION(14 140)
+    endif()
   endif()
 
   foreach(lib
diff --git a/Modules/Platform/Android.cmake b/Modules/Platform/Android.cmake
new file mode 100644
index 0000000..1bdad04
--- /dev/null
+++ b/Modules/Platform/Android.cmake
@@ -0,0 +1,15 @@
+include(Platform/Linux)
+
+# Android has soname, but binary names must end in ".so" so we cannot append
+# a version number.  Also we cannot portably represent symlinks on the host.
+set(CMAKE_PLATFORM_NO_VERSIONED_SONAME 1)
+
+# Android reportedly ignores RPATH, and we cannot predict the install
+# location anyway.
+set(CMAKE_SHARED_LIBRARY_RUNTIME_C_FLAG "")
+
+# Nsight Tegra Visual Studio Edition takes care of
+# prefixing library names with '-l'.
+if(CMAKE_VS_PLATFORM_NAME STREQUAL "Tegra-Android")
+  set(CMAKE_LINK_LIBRARY_FLAG "")
+endif()
diff --git a/Modules/Platform/Darwin.cmake b/Modules/Platform/Darwin.cmake
index e25df1e..e5c5f36 100644
--- a/Modules/Platform/Darwin.cmake
+++ b/Modules/Platform/Darwin.cmake
@@ -70,6 +70,8 @@
     set(_sdk_ver "${CMAKE_MATCH_1}")
   elseif("${_CMAKE_OSX_SYSROOT_ORIG}" MATCHES "^macosx([0-9]+\\.[0-9]+)$")
     set(_sdk_ver "${CMAKE_MATCH_1}")
+  elseif("${_CMAKE_OSX_SYSROOT_ORIG}" STREQUAL "/")
+    set(_sdk_ver "${_CURRENT_OSX_VERSION}")
   else()
     message(FATAL_ERROR
       "CMAKE_OSX_DEPLOYMENT_TARGET is '${CMAKE_OSX_DEPLOYMENT_TARGET}' "
diff --git a/Modules/Platform/QNX-QCC-C.cmake b/Modules/Platform/QNX-QCC-C.cmake
deleted file mode 100644
index e5721a7..0000000
--- a/Modules/Platform/QNX-QCC-C.cmake
+++ /dev/null
@@ -1,4 +0,0 @@
-
-include(Platform/QNX)
-
-__compiler_qcc(C)
diff --git a/Modules/Platform/QNX-QCC-CXX.cmake b/Modules/Platform/QNX-QCC-CXX.cmake
deleted file mode 100644
index e490bbe..0000000
--- a/Modules/Platform/QNX-QCC-CXX.cmake
+++ /dev/null
@@ -1,4 +0,0 @@
-
-include(Platform/QNX)
-
-__compiler_qcc(CXX)
diff --git a/Modules/Platform/QNX.cmake b/Modules/Platform/QNX.cmake
index cc551bd..ebc4609 100644
--- a/Modules/Platform/QNX.cmake
+++ b/Modules/Platform/QNX.cmake
@@ -1,5 +1,8 @@
 set(QNXNTO 1)
 
+include(Platform/GNU)
+unset(CMAKE_LIBRARY_ARCHITECTURE_REGEX)
+
 set(CMAKE_DL_LIBS "")
 
 # Shared libraries with no builtin soname may not be linked safely by
@@ -14,22 +17,3 @@
   set(CMAKE_${type}_LINK_STATIC_C_FLAGS "-Wl,-Bstatic")
   set(CMAKE_${type}_LINK_DYNAMIC_C_FLAGS "-Wl,-Bdynamic")
 endforeach()
-
-include(Platform/GNU)
-unset(CMAKE_LIBRARY_ARCHITECTURE_REGEX)
-
-macro(__compiler_qcc lang)
-  # http://www.qnx.com/developers/docs/6.4.0/neutrino/utilities/q/qcc.html#examples
-  set(CMAKE_${lang}_COMPILE_OPTIONS_TARGET "-V")
-
-  set(CMAKE_INCLUDE_SYSTEM_FLAG_${lang} "-Wp,-isystem,")
-  set(CMAKE_DEPFILE_FLAGS_${lang} "-Wc,-MMD,<DEPFILE>,-MT,<OBJECT>,-MF,<DEPFILE>")
-
-  if (lang STREQUAL CXX)
-    # If the toolchain uses qcc for CMAKE_CXX_COMPILER instead of QCC, the
-    # default for the driver is not c++.
-    set(CMAKE_CXX_COMPILE_OBJECT
-    "<CMAKE_CXX_COMPILER> -lang-c++ <DEFINES> <FLAGS> -o <OBJECT> -c <SOURCE>")
-  endif()
-
-endmacro()
diff --git a/Modules/Platform/Windows-MSVC.cmake b/Modules/Platform/Windows-MSVC.cmake
index 5732170..a72f946 100644
--- a/Modules/Platform/Windows-MSVC.cmake
+++ b/Modules/Platform/Windows-MSVC.cmake
@@ -36,15 +36,14 @@
   set(CMAKE_CL_NOLOGO "/nologo")
 endif()
 
-set(WIN32 1)
-
-if(CMAKE_SYSTEM_NAME MATCHES "WindowsCE")
-  set(CMAKE_CREATE_WIN32_EXE "/subsystem:windowsce /entry:WinMainCRTStartup")
-  set(CMAKE_CREATE_CONSOLE_EXE "/subsystem:windowsce /entry:mainACRTStartup")
-  set(WINCE 1)
+if(CMAKE_SYSTEM_NAME STREQUAL "WindowsCE")
+  set(CMAKE_CREATE_WIN32_EXE "/entry:WinMainCRTStartup")
+  set(CMAKE_CREATE_CONSOLE_EXE "/entry:mainACRTStartup")
+  set(_PLATFORM_LINK_FLAGS " /subsystem:windowsce")
 else()
   set(CMAKE_CREATE_WIN32_EXE "/subsystem:windows")
   set(CMAKE_CREATE_CONSOLE_EXE "/subsystem:console")
+  set(_PLATFORM_LINK_FLAGS "")
 endif()
 
 if(CMAKE_GENERATOR MATCHES "Visual Studio 6")
@@ -85,6 +84,7 @@
   set(MSVC10)
   set(MSVC11)
   set(MSVC12)
+  set(MSVC14)
   set(MSVC60)
   set(MSVC70)
   set(MSVC71)
@@ -92,7 +92,9 @@
   set(MSVC90)
   set(CMAKE_COMPILER_2005)
   set(CMAKE_COMPILER_SUPPORTS_PDBTYPE)
-  if(NOT "${_compiler_version}" VERSION_LESS 18)
+  if(NOT "${_compiler_version}" VERSION_LESS 19)
+    set(MSVC14 1)
+  elseif(NOT "${_compiler_version}" VERSION_LESS 18)
     set(MSVC12 1)
   elseif(NOT "${_compiler_version}" VERSION_LESS 17)
     set(MSVC11 1)
@@ -160,10 +162,23 @@
   if (MSVC_VERSION LESS 1600)
     set(CMAKE_C_STANDARD_LIBRARIES_INIT "${CMAKE_C_STANDARD_LIBRARIES_INIT} corelibc.lib")
   endif ()
+elseif(WINDOWS_PHONE OR WINDOWS_STORE)
+  set(_PLATFORM_DEFINES "/DWIN32")
+  set(_FLAGS_C " /DUNICODE /D_UNICODE")
+  set(_FLAGS_CXX " /DUNICODE /D_UNICODE /GR /EHsc")
+  if(WINDOWS_PHONE)
+    set(CMAKE_C_STANDARD_LIBRARIES_INIT "WindowsPhoneCore.lib RuntimeObject.lib PhoneAppModelHost.lib")
+  elseif(MSVC_C_ARCHITECTURE_ID STREQUAL ARM OR MSVC_CXX_ARCHITECTURE_ID STREQUAL ARM)
+    set(CMAKE_C_STANDARD_LIBRARIES_INIT "kernel32.lib user32.lib")
+  else()
+    set(CMAKE_C_STANDARD_LIBRARIES_INIT "kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib")
+  endif()
 else()
   set(_PLATFORM_DEFINES "/DWIN32")
 
-  if(MSVC_VERSION GREATER 1310)
+  if(MSVC_C_ARCHITECTURE_ID STREQUAL ARM OR MSVC_CXX_ARCHITECTURE_ID STREQUAL ARM)
+    set(CMAKE_C_STANDARD_LIBRARIES_INIT "kernel32.lib user32.lib")
+  elseif(MSVC_VERSION GREATER 1310)
     set(_RTC1 "/RTC1")
     set(_FLAGS_CXX " /GR /EHsc")
     set(CMAKE_C_STANDARD_LIBRARIES_INIT "kernel32.lib user32.lib gdi32.lib winspool.lib shell32.lib ole32.lib oleaut32.lib uuid.lib comdlg32.lib advapi32.lib")
@@ -197,10 +212,12 @@
 # add /debug and /INCREMENTAL:YES to DEBUG and RELWITHDEBINFO also add pdbtype
 # on versions that support it
 set( MSVC_INCREMENTAL_YES_FLAG "")
-if(NOT MSVC_INCREMENTAL_DEFAULT)
-  set( MSVC_INCREMENTAL_YES_FLAG "/INCREMENTAL:YES")
-else()
-  set(  MSVC_INCREMENTAL_YES_FLAG "/INCREMENTAL" )
+if(NOT WINDOWS_PHONE AND NOT WINDOWS_STORE)
+  if(NOT MSVC_INCREMENTAL_DEFAULT)
+    set( MSVC_INCREMENTAL_YES_FLAG "/INCREMENTAL:YES")
+  else()
+    set(  MSVC_INCREMENTAL_YES_FLAG "/INCREMENTAL" )
+  endif()
 endif()
 
 if (CMAKE_COMPILER_SUPPORTS_PDBTYPE)
@@ -235,7 +252,7 @@
     set(_CMAKE_VS_LINK_EXE "<CMAKE_COMMAND> -E vs_link_exe ")
   endif()
   set(CMAKE_${lang}_CREATE_SHARED_LIBRARY
-    "${_CMAKE_VS_LINK_DLL}<CMAKE_LINKER> ${CMAKE_CL_NOLOGO} <OBJECTS> ${CMAKE_START_TEMP_FILE} /out:<TARGET> /implib:<TARGET_IMPLIB> /pdb:<TARGET_PDB> /dll /version:<TARGET_VERSION_MAJOR>.<TARGET_VERSION_MINOR> <LINK_FLAGS> <LINK_LIBRARIES> ${CMAKE_END_TEMP_FILE}")
+    "${_CMAKE_VS_LINK_DLL}<CMAKE_LINKER> ${CMAKE_CL_NOLOGO} <OBJECTS> ${CMAKE_START_TEMP_FILE} /out:<TARGET> /implib:<TARGET_IMPLIB> /pdb:<TARGET_PDB> /dll /version:<TARGET_VERSION_MAJOR>.<TARGET_VERSION_MINOR>${_PLATFORM_LINK_FLAGS} <LINK_FLAGS> <LINK_LIBRARIES> ${CMAKE_END_TEMP_FILE}")
 
   set(CMAKE_${lang}_CREATE_SHARED_MODULE ${CMAKE_${lang}_CREATE_SHARED_LIBRARY})
   set(CMAKE_${lang}_CREATE_STATIC_LIBRARY  "<CMAKE_LINKER> /lib ${CMAKE_CL_NOLOGO} <LINK_FLAGS> /out:<TARGET> <OBJECTS> ")
@@ -249,11 +266,12 @@
 
   set(CMAKE_${lang}_USE_RESPONSE_FILE_FOR_OBJECTS 1)
   set(CMAKE_${lang}_LINK_EXECUTABLE
-    "${_CMAKE_VS_LINK_EXE}<CMAKE_LINKER> ${CMAKE_CL_NOLOGO} <OBJECTS> ${CMAKE_START_TEMP_FILE} /out:<TARGET> /implib:<TARGET_IMPLIB> /pdb:<TARGET_PDB> /version:<TARGET_VERSION_MAJOR>.<TARGET_VERSION_MINOR> <CMAKE_${lang}_LINK_FLAGS> <LINK_FLAGS> <LINK_LIBRARIES>${CMAKE_END_TEMP_FILE}")
+    "${_CMAKE_VS_LINK_EXE}<CMAKE_LINKER> ${CMAKE_CL_NOLOGO} <OBJECTS> ${CMAKE_START_TEMP_FILE} /out:<TARGET> /implib:<TARGET_IMPLIB> /pdb:<TARGET_PDB> /version:<TARGET_VERSION_MAJOR>.<TARGET_VERSION_MINOR>${_PLATFORM_LINK_FLAGS} <CMAKE_${lang}_LINK_FLAGS> <LINK_FLAGS> <LINK_LIBRARIES>${CMAKE_END_TEMP_FILE}")
 
   set(CMAKE_${lang}_FLAGS_INIT "${_PLATFORM_DEFINES}${_PLATFORM_DEFINES_${lang}} /D_WINDOWS /W3${_FLAGS_${lang}}")
   set(CMAKE_${lang}_FLAGS_DEBUG_INIT "/D_DEBUG /MDd /Zi /Ob0 /Od ${_RTC1}")
   set(CMAKE_${lang}_FLAGS_RELEASE_INIT "/MD /O2 /Ob2 /D NDEBUG")
   set(CMAKE_${lang}_FLAGS_RELWITHDEBINFO_INIT "/MD /Zi /O2 /Ob1 /D NDEBUG")
   set(CMAKE_${lang}_FLAGS_MINSIZEREL_INIT "/MD /O1 /Ob1 /D NDEBUG")
+  set(CMAKE_${lang}_LINKER_SUPPORTS_PDB ON)
 endmacro()
diff --git a/Modules/Platform/Windows-df.cmake b/Modules/Platform/Windows-df.cmake
index 8dfb610..211cc9d 100644
--- a/Modules/Platform/Windows-df.cmake
+++ b/Modules/Platform/Windows-df.cmake
@@ -26,7 +26,6 @@
 
 set(CMAKE_COMPILE_RESOURCE "rc <FLAGS> /fo<OBJECT> <SOURCE>")
 
-set(CMAKE_${lang}_COMPILER_LINKER_OPTION_FLAG_EXECUTABLE "/link")
 set(CMAKE_Fortran_LINK_EXECUTABLE
     "<CMAKE_Fortran_COMPILER> ${CMAKE_CL_NOLOGO} ${CMAKE_START_TEMP_FILE} <FLAGS> /exe:<TARGET> <OBJECTS> /link <CMAKE_Fortran_LINK_FLAGS> <LINK_FLAGS> <LINK_LIBRARIES>${CMAKE_END_TEMP_FILE}")
 
diff --git a/Modules/Platform/Windows.cmake b/Modules/Platform/Windows.cmake
index b158a9d..9a937a7 100644
--- a/Modules/Platform/Windows.cmake
+++ b/Modules/Platform/Windows.cmake
@@ -1,5 +1,13 @@
 set(WIN32 1)
 
+if(CMAKE_SYSTEM_NAME STREQUAL "WindowsCE")
+  set(WINCE 1)
+elseif(CMAKE_SYSTEM_NAME STREQUAL "WindowsPhone")
+  set(WINDOWS_PHONE 1)
+elseif(CMAKE_SYSTEM_NAME STREQUAL "WindowsStore")
+  set(WINDOWS_STORE 1)
+endif()
+
 set(CMAKE_STATIC_LIBRARY_PREFIX "")
 set(CMAKE_STATIC_LIBRARY_SUFFIX ".lib")
 set(CMAKE_SHARED_LIBRARY_PREFIX "")          # lib
diff --git a/Modules/Platform/WindowsCE-MSVC.cmake b/Modules/Platform/WindowsCE-MSVC.cmake
deleted file mode 100644
index d28b4ab..0000000
--- a/Modules/Platform/WindowsCE-MSVC.cmake
+++ /dev/null
@@ -1 +0,0 @@
-include(Platform/Windows-MSVC)
diff --git a/Modules/Platform/WindowsPhone-MSVC-C.cmake b/Modules/Platform/WindowsPhone-MSVC-C.cmake
new file mode 100644
index 0000000..ce8060b
--- /dev/null
+++ b/Modules/Platform/WindowsPhone-MSVC-C.cmake
@@ -0,0 +1 @@
+include(Platform/Windows-MSVC-C)
diff --git a/Modules/Platform/WindowsPhone-MSVC-CXX.cmake b/Modules/Platform/WindowsPhone-MSVC-CXX.cmake
new file mode 100644
index 0000000..281eadc
--- /dev/null
+++ b/Modules/Platform/WindowsPhone-MSVC-CXX.cmake
@@ -0,0 +1 @@
+include(Platform/Windows-MSVC-CXX)
diff --git a/Modules/Platform/WindowsPhone.cmake b/Modules/Platform/WindowsPhone.cmake
new file mode 100644
index 0000000..65b2eae
--- /dev/null
+++ b/Modules/Platform/WindowsPhone.cmake
@@ -0,0 +1 @@
+include(Platform/Windows)
diff --git a/Modules/Platform/WindowsStore-MSVC-C.cmake b/Modules/Platform/WindowsStore-MSVC-C.cmake
new file mode 100644
index 0000000..ce8060b
--- /dev/null
+++ b/Modules/Platform/WindowsStore-MSVC-C.cmake
@@ -0,0 +1 @@
+include(Platform/Windows-MSVC-C)
diff --git a/Modules/Platform/WindowsStore-MSVC-CXX.cmake b/Modules/Platform/WindowsStore-MSVC-CXX.cmake
new file mode 100644
index 0000000..281eadc
--- /dev/null
+++ b/Modules/Platform/WindowsStore-MSVC-CXX.cmake
@@ -0,0 +1 @@
+include(Platform/Windows-MSVC-CXX)
diff --git a/Modules/Platform/WindowsStore.cmake b/Modules/Platform/WindowsStore.cmake
new file mode 100644
index 0000000..65b2eae
--- /dev/null
+++ b/Modules/Platform/WindowsStore.cmake
@@ -0,0 +1 @@
+include(Platform/Windows)
diff --git a/Modules/ProcessorCount.cmake b/Modules/ProcessorCount.cmake
index e034a28..8f21adf 100644
--- a/Modules/ProcessorCount.cmake
+++ b/Modules/ProcessorCount.cmake
@@ -103,6 +103,10 @@
         OUTPUT_VARIABLE machinfo_output)
       string(REGEX MATCHALL "Number of CPUs = ([0-9]+)" procs "${machinfo_output}")
       set(count "${CMAKE_MATCH_1}")
+      if(NOT count)
+        string(REGEX MATCHALL "([0-9]+) logical processors" procs "${machinfo_output}")
+        set(count "${CMAKE_MATCH_1}")
+      endif()
       #message("ProcessorCount: trying machinfo '${ProcessorCount_cmd_machinfo}'")
     else()
       find_program(ProcessorCount_cmd_mpsched mpsched)
diff --git a/Modules/TestBigEndian.cmake b/Modules/TestBigEndian.cmake
index 6f32b08..fcb41ab 100644
--- a/Modules/TestBigEndian.cmake
+++ b/Modules/TestBigEndian.cmake
@@ -25,7 +25,7 @@
 #  License text for the above reference.)
 
 macro(TEST_BIG_ENDIAN VARIABLE)
-  if("HAVE_${VARIABLE}" MATCHES "^HAVE_${VARIABLE}$")
+  if(NOT DEFINED HAVE_${VARIABLE})
     message(STATUS "Check if the system is big endian")
     message(STATUS "Searching 16 bit integer")
 
diff --git a/Modules/TestForANSIForScope.cmake b/Modules/TestForANSIForScope.cmake
index de4b1f1..78fff9f 100644
--- a/Modules/TestForANSIForScope.cmake
+++ b/Modules/TestForANSIForScope.cmake
@@ -24,7 +24,7 @@
 # (To distribute this file outside of CMake, substitute the full
 #  License text for the above reference.)
 
-if("CMAKE_ANSI_FOR_SCOPE" MATCHES "^CMAKE_ANSI_FOR_SCOPE$")
+if(NOT DEFINED CMAKE_ANSI_FOR_SCOPE)
   message(STATUS "Check for ANSI scope")
   try_compile(CMAKE_ANSI_FOR_SCOPE  ${CMAKE_BINARY_DIR}
     ${CMAKE_ROOT}/Modules/TestForAnsiForScope.cxx
diff --git a/Modules/TestForSSTREAM.cmake b/Modules/TestForSSTREAM.cmake
index 8977583..fe18ea2 100644
--- a/Modules/TestForSSTREAM.cmake
+++ b/Modules/TestForSSTREAM.cmake
@@ -23,7 +23,7 @@
 # (To distribute this file outside of CMake, substitute the full
 #  License text for the above reference.)
 
-if("CMAKE_HAS_ANSI_STRING_STREAM" MATCHES "^CMAKE_HAS_ANSI_STRING_STREAM$")
+if(NOT DEFINED CMAKE_HAS_ANSI_STRING_STREAM)
   message(STATUS "Check for sstream")
   try_compile(CMAKE_HAS_ANSI_STRING_STREAM  ${CMAKE_BINARY_DIR}
     ${CMAKE_ROOT}/Modules/TestForSSTREAM.cxx
diff --git a/Modules/TestForSTDNamespace.cmake b/Modules/TestForSTDNamespace.cmake
index e43b75d..0d90774 100644
--- a/Modules/TestForSTDNamespace.cmake
+++ b/Modules/TestForSTDNamespace.cmake
@@ -23,7 +23,7 @@
 # (To distribute this file outside of CMake, substitute the full
 #  License text for the above reference.)
 
-if("CMAKE_STD_NAMESPACE" MATCHES "^CMAKE_STD_NAMESPACE$")
+if(NOT DEFINED CMAKE_STD_NAMESPACE)
   message(STATUS "Check for STD namespace")
   try_compile(CMAKE_STD_NAMESPACE  ${CMAKE_BINARY_DIR}
     ${CMAKE_ROOT}/Modules/TestForSTDNamespace.cxx
diff --git a/Modules/UseSWIG.cmake b/Modules/UseSWIG.cmake
index 918e2ec..31ab48d 100644
--- a/Modules/UseSWIG.cmake
+++ b/Modules/UseSWIG.cmake
@@ -73,7 +73,7 @@
   set(SWIG_MODULE_${name}_SWIG_LANGUAGE_FLAG "${swig_lowercase_language}")
 
   set(SWIG_MODULE_${name}_REAL_NAME "${name}")
-  if (CMAKE_SWIG_FLAGS MATCHES "-noproxy")
+  if (";${CMAKE_SWIG_FLAGS};" MATCHES ";-noproxy;")
     set (SWIG_MODULE_${name}_NOPROXY TRUE)
   endif ()
   if("${SWIG_MODULE_${name}_LANGUAGE}" STREQUAL "UNKNOWN")
diff --git a/Modules/UsewxWidgets.cmake b/Modules/UsewxWidgets.cmake
index f2f260d..b3633a6 100644
--- a/Modules/UsewxWidgets.cmake
+++ b/Modules/UsewxWidgets.cmake
@@ -88,8 +88,11 @@
   endif()
 
   if   (wxWidgets_CXX_FLAGS)
-    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${wxWidgets_CXX_FLAGS}")
-    MSG("wxWidgets_CXX_FLAGS=${wxWidgets_CXX_FLAGS}")
+    # Flags are expected to be a string here, not a list.
+    string(REPLACE ";" " " wxWidgets_CXX_FLAGS_str "${wxWidgets_CXX_FLAGS}")
+    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${wxWidgets_CXX_FLAGS_str}")
+    MSG("wxWidgets_CXX_FLAGS=${wxWidgets_CXX_FLAGS_str}")
+    unset(wxWidgets_CXX_FLAGS_str)
   endif()
 
   # DEPRECATED JW
diff --git a/Modules/WriteBasicConfigVersionFile.cmake b/Modules/WriteBasicConfigVersionFile.cmake
index 7d28e95..bf55eb9 100644
--- a/Modules/WriteBasicConfigVersionFile.cmake
+++ b/Modules/WriteBasicConfigVersionFile.cmake
@@ -6,7 +6,10 @@
 #
 # ::
 #
-#   WRITE_BASIC_CONFIG_VERSION_FILE( filename [VERSION major.minor.patch] COMPATIBILITY (AnyNewerVersion|SameMajorVersion) )
+#   WRITE_BASIC_CONFIG_VERSION_FILE( filename
+#     [VERSION major.minor.patch]
+#     COMPATIBILITY (AnyNewerVersion|SameMajorVersion)
+#     )
 #
 #
 #
diff --git a/Modules/WriteCompilerDetectionHeader.cmake b/Modules/WriteCompilerDetectionHeader.cmake
index 6e64cd2..86137e2 100644
--- a/Modules/WriteCompilerDetectionHeader.cmake
+++ b/Modules/WriteCompilerDetectionHeader.cmake
@@ -52,7 +52,15 @@
 # Feature Test Macros
 # ===================
 #
-# For each compiler, a preprocessor test of the compiler version is generated
+# For each compiler, a preprocessor macro is generated matching
+# ``<PREFIX>_COMPILER_IS_<compiler>`` which has the content either ``0``
+# or ``1``, depending on the compiler in use. Preprocessor macros for
+# compiler version components are generated matching
+# ``<PREFIX>_COMPILER_VERSION_MAJOR`` ``<PREFIX>_COMPILER_VERSION_MINOR``
+# and ``<PREFIX>_COMPILER_VERSION_PATCH`` containing decimal values
+# for the corresponding compiler version components, if defined.
+#
+# A preprocessor test is generated based on the compiler version
 # denoting whether each feature is enabled.  A preprocessor macro
 # matching ``<PREFIX>_COMPILER_<FEATURE>``, where ``<FEATURE>`` is the
 # upper-case ``<feature>`` name, is generated to contain the value
@@ -91,14 +99,14 @@
 #
 # .. code-block:: c++
 #
-#    class MyClass ClimbingStats_DECL_CXX_FINAL
+#    class MyClass ClimbingStats_FINAL
 #    {
-#        ClimbingStats_DECL_CXX_CONSTEXPR int someInterface() { return 42; }
+#        ClimbingStats_CONSTEXPR int someInterface() { return 42; }
 #    };
 #
-# The ``ClimbingStats_DECL_CXX_FINAL`` macro will expand to ``final`` if the
+# The ``ClimbingStats_FINAL`` macro will expand to ``final`` if the
 # compiler (and its flags) support the ``cxx_final`` feature, and the
-# ``ClimbingStats_DECL_CXX_CONSTEXPR`` macro will expand to ``constexpr``
+# ``ClimbingStats_CONSTEXPR`` macro will expand to ``constexpr``
 # if ``cxx_constexpr`` is supported.
 #
 # The following features generate corresponding symbol defines:
@@ -138,6 +146,16 @@
 # ``[[deprecated]]`` attribute or a compiler-specific decorator such
 # as ``__attribute__((__deprecated__))`` used by GNU compilers.
 #
+# The ``cxx_alignas`` feature provides a macro definition
+# ``<PREFIX>_ALIGNAS`` which expands to either the standard ``alignas``
+# decorator or a compiler-specific decorator such as
+# ``__attribute__ ((__aligned__))`` used by GNU compilers.
+#
+# The ``cxx_alignof`` feature provides a macro definition
+# ``<PREFIX>_ALIGNOF`` which expands to either the standard ``alignof``
+# decorator or a compiler-specific decorator such as ``__alignof__``
+# used by GNU compilers.
+#
 # ============================= ================================ =====================
 #           Feature                          Define                     Symbol
 # ============================= ================================ =====================
@@ -187,6 +205,8 @@
   foreach(feature ${ARGN})
     set(_cmake_feature_test_${CompilerId}_${feature} ${_cmake_feature_test_${feature}} PARENT_SCOPE)
   endforeach()
+  include("${CMAKE_ROOT}/Modules/Compiler/${CompilerId}-DetermineCompiler.cmake" OPTIONAL)
+  set(_compiler_id_version_compute_${CompilerId} ${_compiler_id_version_compute} PARENT_SCOPE)
 endfunction()
 
 function(write_compiler_detection_header
@@ -215,22 +235,44 @@
     message(FATAL_ERROR "Unparsed arguments: ${_WCD_UNPARSED_ARGUMENTS}")
   endif()
 
+  if (prefix_arg STREQUAL "")
+    message(FATAL_ERROR "A prefix must be specified")
+  endif()
+  string(MAKE_C_IDENTIFIER ${prefix_arg} cleaned_prefix)
+  if (NOT prefix_arg STREQUAL cleaned_prefix)
+    message(FATAL_ERROR "The prefix must be a valid C identifier.")
+  endif()
+
   if(NOT _WCD_VERSION)
     set(_WCD_VERSION ${CMAKE_MINIMUM_REQUIRED_VERSION})
   endif()
-  if (_WCD_VERSION VERSION_LESS 3.1.0) # Version which introduced this function
-    message(FATAL_ERROR "VERSION parameter too low.")
+  set(_min_version 3.1.0) # Version which introduced this function
+  if (_WCD_VERSION VERSION_LESS _min_version)
+    set(err "VERSION compatibility for write_compiler_detection_header is set to ${_WCD_VERSION}, which is too low.")
+    set(err "${err}  It must be set to at least ${_min_version}.  ")
+    set(err "${err}  Either set the VERSION parameter to the write_compiler_detection_header function, or update")
+    set(err "${err} your minimum required CMake version with the cmake_minimum_required command.")
+    message(FATAL_ERROR "${err}")
   endif()
 
   set(compilers
     GNU
     Clang
   )
+
+  set(_hex_compilers ADSP Borland Embarcadero SunPro)
+
   foreach(_comp ${_WCD_COMPILERS})
     list(FIND compilers ${_comp} idx)
     if (idx EQUAL -1)
       message(FATAL_ERROR "Unsupported compiler ${_comp}.")
     endif()
+    if (NOT _need_hex_conversion)
+      list(FIND _hex_compilers ${_comp} idx)
+      if (NOT idx EQUAL -1)
+        set(_need_hex_conversion TRUE)
+      endif()
+    endif()
   endforeach()
 
   set(file_content "
@@ -244,6 +286,21 @@
     set(file_content "${file_content}\n${_WCD_PROLOG}\n")
   endif()
 
+  if (_need_hex_conversion)
+    set(file_content "${file_content}
+#define ${prefix_arg}_DEC(X) (X)
+#define ${prefix_arg}_HEX(X) ( \\
+    ((X)>>28 & 0xF) * 10000000 + \\
+    ((X)>>24 & 0xF) *  1000000 + \\
+    ((X)>>20 & 0xF) *   100000 + \\
+    ((X)>>16 & 0xF) *    10000 + \\
+    ((X)>>12 & 0xF) *     1000 + \\
+    ((X)>>8  & 0xF) *      100 + \\
+    ((X)>>4  & 0xF) *       10 + \\
+    ((X)     & 0xF) \\
+    )\n")
+  endif()
+
   foreach(feature ${_WCD_FEATURES})
     if (feature MATCHES "^cxx_")
       list(APPEND _langs CXX)
@@ -287,6 +344,21 @@
 #    if !(${_cmake_oldestSupported_${compiler}})
 #      error Unsupported compiler version
 #    endif\n")
+
+      set(PREFIX ${prefix_arg}_)
+      if (_need_hex_conversion)
+        set(MACRO_DEC ${prefix_arg}_DEC)
+        set(MACRO_HEX ${prefix_arg}_HEX)
+      else()
+        set(MACRO_DEC)
+        set(MACRO_HEX)
+      endif()
+      string(CONFIGURE "${_compiler_id_version_compute_${compiler}}" VERSION_BLOCK @ONLY)
+      set(file_content "${file_content}${VERSION_BLOCK}\n")
+      set(PREFIX)
+      set(MACRO_DEC)
+      set(MACRO_HEX)
+
       set(pp_if "elif")
       foreach(feature ${${_lang}_features})
         string(TOUPPER ${feature} feature_upper)
@@ -322,7 +394,7 @@
 \n")
       endif()
       if (feature STREQUAL cxx_constexpr)
-        set(def_value "${prefix_arg}_DECL_${feature_upper}")
+        set(def_value "${prefix_arg}_CONSTEXPR")
         set(file_content "${file_content}
 #  if ${def_name}
 #    define ${def_value} constexpr
@@ -332,7 +404,7 @@
 \n")
       endif()
       if (feature STREQUAL cxx_final)
-        set(def_value "${prefix_arg}_DECL_${feature_upper}")
+        set(def_value "${prefix_arg}_FINAL")
         set(file_content "${file_content}
 #  if ${def_name}
 #    define ${def_value} final
@@ -342,7 +414,7 @@
 \n")
       endif()
       if (feature STREQUAL cxx_override)
-        set(def_value "${prefix_arg}_DECL_${feature_upper}")
+        set(def_value "${prefix_arg}_OVERRIDE")
         set(file_content "${file_content}
 #  if ${def_name}
 #    define ${def_value} override
@@ -364,7 +436,7 @@
         set(file_content "${file_content}
 #  if ${def_name}
 #    define ${def_value} alignas(X)
-#  elif ${prefix_arg}_COMPILER_IS_GNU
+#  elif ${prefix_arg}_COMPILER_IS_GNU || ${prefix_arg}_COMPILER_IS_Clang
 #    define ${def_value} __attribute__ ((__aligned__(X)))
 #  else
 #    define ${def_value}
@@ -376,7 +448,7 @@
         set(file_content "${file_content}
 #  if ${def_name}
 #    define ${def_value} alignof(X)
-#  elif ${prefix_arg}_COMPILER_IS_GNU
+#  elif ${prefix_arg}_COMPILER_IS_GNU || ${prefix_arg}_COMPILER_IS_Clang
 #    define ${def_value} __alignof__(X)
 #  endif
 \n")
@@ -431,10 +503,10 @@
 #    if ${def_name}
 #      define ${def_value} [[deprecated]]
 #      define ${def_value}_MSG(MSG) [[deprecated(MSG)]]
-#    elif defined(__GNUC__) || defined(__clang__)
+#    elif ${prefix_arg}_COMPILER_IS_GNU || ${prefix_arg}_COMPILER_IS_Clang
 #      define ${def_value} __attribute__((__deprecated__))
 #      define ${def_value}_MSG(MSG) __attribute__((__deprecated__(MSG)))
-#    elif defined(_MSC_VER)
+#    elif ${prefix_arg}_COMPILER_IS_MSVC
 #      define ${def_value} __declspec(deprecated)
 #      define ${def_value}_MSG(MSG) __declspec(deprecated(MSG))
 #    else
diff --git a/README.rst b/README.rst
index e91b209..e8524f8 100644
--- a/README.rst
+++ b/README.rst
@@ -75,6 +75,22 @@
 
 .. _`Running CMake`: http://www.cmake.org/cmake/help/runningcmake.html
 
+Reporting Bugs
+==============
+
+If you have found a bug:
+
+1. If you have a patch, please read the `CONTRIBUTING.rst`_ document.
+
+2. Otherwise, please join the the `CMake Users List`_ and ask about
+   the expected and observed behaviors to determine if it is really
+   a bug.
+
+3. Finally, if the issue is not resolved by the above steps, open
+   an entry in the `CMake Issue Tracker`_.
+
+.. _`CMake Issue Tracker`: http://www.cmake.org/Bug
+
 Contributing
 ============
 
diff --git a/Source/CMakeLists.txt b/Source/CMakeLists.txt
index fe6cc1b..f9405b3 100644
--- a/Source/CMakeLists.txt
+++ b/Source/CMakeLists.txt
@@ -308,6 +308,7 @@
   cmTest.h
   cmTestGenerator.cxx
   cmTestGenerator.h
+  cmUuid.cxx
   cmVariableWatch.cxx
   cmVariableWatch.h
   cmVersion.cxx
@@ -426,6 +427,8 @@
       cmGlobalVisualStudio11Generator.cxx
       cmGlobalVisualStudio12Generator.h
       cmGlobalVisualStudio12Generator.cxx
+      cmGlobalVisualStudio14Generator.h
+      cmGlobalVisualStudio14Generator.cxx
       cmGlobalVisualStudioGenerator.cxx
       cmGlobalVisualStudioGenerator.h
       cmIDEFlagTable.h
@@ -448,7 +451,7 @@
 endif ()
 
 # Watcom support
-if(WIN32 OR "${CMAKE_SYSTEM_NAME}" STREQUAL "Linux")
+if(WIN32 OR CMAKE_SYSTEM_NAME STREQUAL "Linux")
   set_property(SOURCE cmake.cxx APPEND PROPERTY COMPILE_DEFINITIONS CMAKE_USE_WMAKE)
   list(APPEND SRCS
     cmGlobalWatcomWMakeGenerator.cxx
@@ -518,6 +521,7 @@
   CTest/cmParseMumpsCoverage.cxx
   CTest/cmParseCacheCoverage.cxx
   CTest/cmParseGTMCoverage.cxx
+  CTest/cmParseJacocoCoverage.cxx
   CTest/cmParsePHPCoverage.cxx
   CTest/cmParseCoberturaCoverage.cxx
   CTest/cmCTestEmptyBinaryDirectoryCommand.cxx
@@ -574,11 +578,16 @@
   CPack/cmCPackGenerator.cxx
   CPack/cmCPackLog.cxx
   CPack/cmCPackNSISGenerator.cxx
+  CPack/IFW/cmCPackIFWPackage.cxx
+  CPack/IFW/cmCPackIFWInstaller.cxx
+  CPack/IFW/cmCPackIFWGenerator.cxx
   CPack/cmCPackSTGZGenerator.cxx
   CPack/cmCPackTGZGenerator.cxx
+  CPack/cmCPackTXZGenerator.cxx
   CPack/cmCPackTarBZip2Generator.cxx
   CPack/cmCPackTarCompressGenerator.cxx
   CPack/cmCPackZIPGenerator.cxx
+  CPack/cmCPack7zGenerator.cxx
   )
 
 if(CYGWIN)
@@ -598,13 +607,14 @@
 if(WIN32)
   set(CPACK_SRCS ${CPACK_SRCS}
     CPack/WiX/cmCPackWIXGenerator.cxx
-    CPack/WiX/cmWIXSourceWriter.cxx
+    CPack/WiX/cmWIXAccessControlList.cxx
     CPack/WiX/cmWIXDirectoriesSourceWriter.cxx
     CPack/WiX/cmWIXFeaturesSourceWriter.cxx
     CPack/WiX/cmWIXFilesSourceWriter.cxx
-    CPack/WiX/cmWIXRichTextFormatWriter.cxx
     CPack/WiX/cmWIXPatch.cxx
     CPack/WiX/cmWIXPatchParser.cxx
+    CPack/WiX/cmWIXRichTextFormatWriter.cxx
+    CPack/WiX/cmWIXSourceWriter.cxx
   )
 endif()
 
diff --git a/Source/CMakeVersion.cmake b/Source/CMakeVersion.cmake
index 34aefb4..716f229 100644
--- a/Source/CMakeVersion.cmake
+++ b/Source/CMakeVersion.cmake
@@ -1,5 +1,5 @@
 # CMake version number components.
 set(CMake_VERSION_MAJOR 3)
-set(CMake_VERSION_MINOR 0)
-set(CMake_VERSION_PATCH 20140609)
-#set(CMake_VERSION_RC 1)
+set(CMake_VERSION_MINOR 1)
+set(CMake_VERSION_PATCH 0)
+set(CMake_VERSION_RC 1)
diff --git a/Source/CPack/IFW/cmCPackIFWGenerator.cxx b/Source/CPack/IFW/cmCPackIFWGenerator.cxx
new file mode 100644
index 0000000..7f06e2d
--- /dev/null
+++ b/Source/CPack/IFW/cmCPackIFWGenerator.cxx
@@ -0,0 +1,552 @@
+/*============================================================================
+  CMake - Cross Platform Makefile Generator
+  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
+
+  Distributed under the OSI-approved BSD License (the "License");
+  see accompanying file Copyright.txt for details.
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the License for more information.
+============================================================================*/
+
+#include "cmCPackIFWGenerator.h"
+
+#include "cmCPackIFWPackage.h"
+#include "cmCPackIFWInstaller.h"
+
+#include <CPack/cmCPackLog.h>
+#include <CPack/cmCPackComponentGroup.h>
+
+#include <cmsys/SystemTools.hxx>
+#include <cmsys/Glob.hxx>
+#include <cmsys/Directory.hxx>
+#include <cmsys/RegularExpression.hxx>
+
+#include <cmGlobalGenerator.h>
+#include <cmLocalGenerator.h>
+#include <cmSystemTools.h>
+#include <cmMakefile.h>
+#include <cmGeneratedFileStream.h>
+#include <cmXMLSafe.h>
+
+//----------------------------------------------------------------------------
+cmCPackIFWGenerator::cmCPackIFWGenerator()
+{
+}
+
+//----------------------------------------------------------------------------
+cmCPackIFWGenerator::~cmCPackIFWGenerator()
+{
+}
+
+//----------------------------------------------------------------------------
+int cmCPackIFWGenerator::PackageFiles()
+{
+  cmCPackLogger(cmCPackLog::LOG_OUTPUT, "- Configuration" << std::endl);
+
+  // Installer configuragion
+  Installer.GenerateInstallerFile();
+
+  // Packages configuration
+  Installer.GeneratePackageFiles();
+
+  std::string ifwTLD = this->GetOption("CPACK_TOPLEVEL_DIRECTORY");
+  std::string ifwTmpFile = ifwTLD;
+  ifwTmpFile += "/IFWOutput.log";
+
+  // Run repogen
+  if (!Installer.Repositories.empty())
+    {
+    std::string ifwCmd = RepoGen;
+    ifwCmd += " -c " + this->toplevel + "/config/config.xml";
+    ifwCmd += " -p " + this->toplevel + "/packages";
+
+    if(!PkgsDirsVector.empty())
+      {
+      for(std::vector<std::string>::iterator it = PkgsDirsVector.begin();
+          it != PkgsDirsVector.end(); ++it)
+        {
+        ifwCmd += " -p " + *it;
+        }
+      }
+
+    if (!OnlineOnly && !DownloadedPackages.empty())
+      {
+      ifwCmd += " -i ";
+      std::set<cmCPackIFWPackage*>::iterator it
+        = DownloadedPackages.begin();
+      ifwCmd += (*it)->Name;
+      ++it;
+      while(it != DownloadedPackages.end())
+        {
+        ifwCmd += "," + (*it)->Name;
+        ++it;
+        }
+      }
+    ifwCmd += " " + this->toplevel + "/repository";
+    cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Execute: " << ifwCmd
+                  << std::endl);
+    std::string output;
+    int retVal = 1;
+    cmCPackLogger(cmCPackLog::LOG_OUTPUT,
+                  "- Generate repository" << std::endl);
+    bool res = cmSystemTools::RunSingleCommand(
+      ifwCmd.c_str(), &output, &retVal, 0, this->GeneratorVerbose, 0);
+    if ( !res || retVal )
+      {
+      cmGeneratedFileStream ofs(ifwTmpFile.c_str());
+      ofs << "# Run command: " << ifwCmd << std::endl
+          << "# Output:" << std::endl
+          << output << std::endl;
+      cmCPackLogger(cmCPackLog::LOG_ERROR, "Problem running IFW command: "
+                    << ifwCmd << std::endl
+                    << "Please check " << ifwTmpFile << " for errors"
+                    << std::endl);
+      return 0;
+      }
+    cmCPackLogger(cmCPackLog::LOG_OUTPUT, "- repository: " << this->toplevel
+                  << "/repository generated" << std::endl);
+    }
+
+  // Run binary creator
+  {
+  std::string ifwCmd = BinCreator;
+  ifwCmd += " -c " + this->toplevel + "/config/config.xml";
+  ifwCmd += " -p " + this->toplevel + "/packages";
+
+  if(!PkgsDirsVector.empty())
+    {
+    for(std::vector<std::string>::iterator it = PkgsDirsVector.begin();
+        it != PkgsDirsVector.end(); ++it)
+      {
+      ifwCmd += " -p " + *it;
+      }
+    }
+
+  if (OnlineOnly)
+    {
+    ifwCmd += " --online-only";
+    }
+  else if (!DownloadedPackages.empty() && !Installer.Repositories.empty())
+    {
+    ifwCmd += " -e ";
+    std::set<cmCPackIFWPackage*>::iterator it
+      = DownloadedPackages.begin();
+    ifwCmd += (*it)->Name;
+    ++it;
+    while(it != DownloadedPackages.end())
+      {
+      ifwCmd += "," + (*it)->Name;
+      ++it;
+      }
+    }
+  else if (!DependentPackages.empty())
+    {
+    ifwCmd += " -i ";
+    // Binary
+    std::set<cmCPackIFWPackage*>::iterator bit = BinaryPackages.begin();
+    while(bit != BinaryPackages.end())
+      {
+      ifwCmd += (*bit)->Name + ",";
+      ++bit;
+      }
+    // Depend
+    DependenceMap::iterator it = DependentPackages.begin();
+    ifwCmd += it->second.Name;
+    ++it;
+    while(it != DependentPackages.end())
+      {
+      ifwCmd += "," + it->second.Name;
+      ++it;
+      }
+    }
+  // TODO: set correct name for multipackages
+  if (this->packageFileNames.size() > 0)
+    {
+    ifwCmd += " " + packageFileNames[0];
+    }
+  else
+    {
+    ifwCmd += " installer";
+    }
+  cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Execute: " << ifwCmd
+                << std::endl);
+  std::string output;
+  int retVal = 1;
+  cmCPackLogger(cmCPackLog::LOG_OUTPUT, "- Generate package" << std::endl);
+  bool res = cmSystemTools::RunSingleCommand(
+    ifwCmd.c_str(), &output, &retVal, 0, this->GeneratorVerbose, 0);
+  if ( !res || retVal )
+    {
+    cmGeneratedFileStream ofs(ifwTmpFile.c_str());
+    ofs << "# Run command: " << ifwCmd << std::endl
+        << "# Output:" << std::endl
+        << output << std::endl;
+    cmCPackLogger(cmCPackLog::LOG_ERROR, "Problem running IFW command: "
+                  << ifwCmd << std::endl
+                  << "Please check " << ifwTmpFile << " for errors"
+                  << std::endl);
+    return 0;
+    }
+  }
+
+  return 1;
+}
+
+//----------------------------------------------------------------------------
+const char *cmCPackIFWGenerator::GetPackagingInstallPrefix()
+{
+  const char *defPrefix = cmCPackGenerator::GetPackagingInstallPrefix();
+
+  std::string tmpPref = defPrefix ? defPrefix : "";
+
+  if(this->Components.empty())
+    {
+    tmpPref += "packages/" + GetRootPackageName() + "/data";
+    }
+
+  this->SetOption("CPACK_IFW_PACKAGING_INSTALL_PREFIX", tmpPref.c_str());
+
+  return this->GetOption("CPACK_IFW_PACKAGING_INSTALL_PREFIX");
+}
+
+//----------------------------------------------------------------------------
+const char *cmCPackIFWGenerator::GetOutputExtension()
+{
+  const char *suffix = this->GetOption("CMAKE_EXECUTABLE_SUFFIX");
+  return suffix ? suffix : cmCPackGenerator::GetOutputExtension();
+}
+
+//----------------------------------------------------------------------------
+int cmCPackIFWGenerator::InitializeInternal()
+{
+  // Search Qt Installer Framework tools
+
+  const std::string BinCreatorOpt = "CPACK_IFW_BINARYCREATOR_EXECUTABLE";
+  const std::string RepoGenOpt = "CPACK_IFW_REPOGEN_EXECUTABLE";
+
+  if(!this->IsSet(BinCreatorOpt) ||
+     !this->IsSet(RepoGenOpt))
+    {
+    this->ReadListFile("CPackIFW.cmake");
+    }
+
+  // Look 'binarycreator' executable (needs)
+
+  const char *BinCreatorStr = this->GetOption(BinCreatorOpt);
+  if(!BinCreatorStr || cmSystemTools::IsNOTFOUND(BinCreatorStr))
+    {
+    BinCreator = "";
+    }
+  else
+    {
+    BinCreator = BinCreatorStr;
+    }
+
+  if (BinCreator.empty())
+    {
+    cmCPackLogger(cmCPackLog::LOG_ERROR,
+                  "Cannot find QtIFW compiler \"binarycreator\": "
+                  "likely it is not installed, or not in your PATH"
+                  << std::endl);
+    return 0;
+    }
+
+  // Look 'repogen' executable (optional)
+
+  const char *RepoGenStr = this->GetOption(RepoGenOpt);
+  if(!RepoGenStr || cmSystemTools::IsNOTFOUND(RepoGenStr))
+    {
+    RepoGen = "";
+    }
+  else
+    {
+    RepoGen = RepoGenStr;
+    }
+
+  // Variables that Change Behavior
+
+  // Resolve duplicate names
+  ResolveDuplicateNames = this->IsOn("CPACK_IFW_RESOLVE_DUPLICATE_NAMES");
+
+  // Additional packages dirs
+  PkgsDirsVector.clear();
+  if(const char* dirs = this->GetOption("CPACK_IFW_PACKAGES_DIRECTORIES"))
+    {
+    cmSystemTools::ExpandListArgument(dirs,
+                                      PkgsDirsVector);
+    }
+
+  // Installer
+  Installer.Generator = this;
+  Installer.ConfigureFromOptions();
+
+  if (const char* ifwDownloadAll =
+      this->GetOption("CPACK_IFW_DOWNLOAD_ALL"))
+    {
+    OnlineOnly = cmSystemTools::IsOn(ifwDownloadAll);
+    }
+  else if (const char* cpackDownloadAll =
+           this->GetOption("CPACK_DOWNLOAD_ALL"))
+    {
+    OnlineOnly = cmSystemTools::IsOn(cpackDownloadAll);
+    }
+  else
+    {
+    OnlineOnly = false;
+    }
+
+  if (!Installer.Repositories.empty() && RepoGen.empty()) {
+  cmCPackLogger(cmCPackLog::LOG_ERROR,
+                "Cannot find QtIFW repository generator \"repogen\": "
+                "likely it is not installed, or not in your PATH"
+                << std::endl);
+  return 0;
+  }
+
+  return this->Superclass::InitializeInternal();
+}
+
+//----------------------------------------------------------------------------
+std::string
+cmCPackIFWGenerator::GetComponentInstallDirNameSuffix(
+  const std::string& componentName)
+{
+  const std::string prefix = "packages/";
+  const std::string suffix = "/data";
+
+  if (componentPackageMethod == ONE_PACKAGE) {
+  return std::string(prefix + GetRootPackageName() + suffix);
+  }
+
+  return prefix
+    + GetComponentPackageName(&Components[componentName])
+    + suffix;
+}
+
+//----------------------------------------------------------------------------
+cmCPackComponent*
+cmCPackIFWGenerator::GetComponent(const std::string &projectName,
+                                  const std::string &componentName)
+{
+  ComponentsMap::iterator cit = Components.find(componentName);
+  if ( cit != Components.end() ) return &(cit->second);
+
+  cmCPackComponent* component
+    = cmCPackGenerator::GetComponent(projectName, componentName);
+  if(!component) return component;
+
+  std::string name = GetComponentPackageName(component);
+  PackagesMap::iterator pit = Packages.find(name);
+  if(pit != Packages.end()) return component;
+
+  cmCPackIFWPackage *package = &Packages[name];
+  package->Name = name;
+  package->Generator = this;
+  if(package->ConfigureFromComponent(component))
+    {
+    package->Installer = &Installer;
+    Installer.Packages.insert(
+      std::pair<std::string, cmCPackIFWPackage*>(
+        name, package));
+    ComponentPackages.insert(
+      std::pair<cmCPackComponent*, cmCPackIFWPackage*>(
+        component, package));
+    if(component->IsDownloaded)
+      {
+      DownloadedPackages.insert(package);
+      }
+    else
+      {
+      BinaryPackages.insert(package);
+      }
+    }
+  else
+    {
+    Packages.erase(name);
+    cmCPackLogger(cmCPackLog::LOG_ERROR,
+                  "Cannot configure package \"" << name <<
+                  "\" for component \"" << component->Name << "\""
+                  << std::endl);
+    }
+
+  return component;
+}
+
+//----------------------------------------------------------------------------
+cmCPackComponentGroup*
+cmCPackIFWGenerator::GetComponentGroup(const std::string &projectName,
+                                       const std::string &groupName)
+{
+  cmCPackComponentGroup* group
+    = cmCPackGenerator::GetComponentGroup(projectName, groupName);
+  if(!group) return group;
+
+  std::string name = GetGroupPackageName(group);
+  PackagesMap::iterator pit = Packages.find(name);
+  if(pit != Packages.end()) return group;
+
+  cmCPackIFWPackage *package = &Packages[name];
+  package->Name = name;
+  package->Generator = this;
+  if(package->ConfigureFromGroup(group))
+    {
+    package->Installer = &Installer;
+    Installer.Packages.insert(
+      std::pair<std::string, cmCPackIFWPackage*>(
+        name, package));
+    GroupPackages.insert(
+      std::pair<cmCPackComponentGroup*, cmCPackIFWPackage*>(
+        group, package));
+    BinaryPackages.insert(package);
+    }
+  else
+    {
+    Packages.erase(name);
+    cmCPackLogger(cmCPackLog::LOG_ERROR,
+                  "Cannot configure package \"" << name <<
+                  "\" for component group \"" << group->Name << "\""
+                  << std::endl);
+    }
+  return group;
+}
+
+//----------------------------------------------------------------------------
+enum cmCPackGenerator::CPackSetDestdirSupport
+cmCPackIFWGenerator::SupportsSetDestdir() const
+{
+  return cmCPackGenerator::SETDESTDIR_SHOULD_NOT_BE_USED;
+}
+
+//----------------------------------------------------------------------------
+bool cmCPackIFWGenerator::SupportsAbsoluteDestination() const
+{
+  return false;
+}
+
+//----------------------------------------------------------------------------
+bool cmCPackIFWGenerator::SupportsComponentInstallation() const
+{
+  return true;
+}
+
+//----------------------------------------------------------------------------
+bool cmCPackIFWGenerator::IsOnePackage() const
+{
+  return componentPackageMethod == ONE_PACKAGE;
+}
+
+//----------------------------------------------------------------------------
+std::string cmCPackIFWGenerator::GetRootPackageName()
+{
+  // Default value
+  std::string name = "root";
+  if (const char* optIFW_PACKAGE_GROUP =
+      this->GetOption("CPACK_IFW_PACKAGE_GROUP"))
+    {
+    // Configure from root group
+    cmCPackIFWPackage package;
+    package.Generator = this;
+    package.ConfigureFromGroup(optIFW_PACKAGE_GROUP);
+    name = package.Name;
+    }
+  else if (const char* optIFW_PACKAGE_NAME =
+           this->GetOption("CPACK_IFW_PACKAGE_NAME"))
+    {
+    // Configure from root package name
+    name = optIFW_PACKAGE_NAME;
+    }
+  else if (const char* optPACKAGE_NAME =
+           this->GetOption("CPACK_PACKAGE_NAME"))
+    {
+    // Configure from package name
+    name = optPACKAGE_NAME;
+    }
+  return name;
+}
+
+//----------------------------------------------------------------------------
+std::string
+cmCPackIFWGenerator::GetGroupPackageName(cmCPackComponentGroup *group) const
+{
+  std::string name;
+  if (!group) return name;
+  if (cmCPackIFWPackage* package = GetGroupPackage(group))
+    {
+    return package->Name;
+    }
+  const char* option = GetOption(
+    "CPACK_IFW_COMPONENT_GROUP_"
+    + cmsys::SystemTools::UpperCase(group->Name)
+    + "_NAME");
+  name = option ? option : group->Name;
+  if(group->ParentGroup)
+    {
+    cmCPackIFWPackage* package = GetGroupPackage(group->ParentGroup);
+    bool dot = !ResolveDuplicateNames;
+    if(dot && name.substr(0, package->Name.size()) == package->Name)
+      {
+      dot = false;
+      }
+    if(dot)
+      {
+      name = package->Name + "." + name;
+      }
+    }
+  return name;
+}
+
+//----------------------------------------------------------------------------
+std::string cmCPackIFWGenerator::GetComponentPackageName(
+  cmCPackComponent *component) const
+{
+  std::string name;
+  if (!component) return name;
+  if (cmCPackIFWPackage* package = GetComponentPackage(component))
+    {
+    return package->Name;
+    }
+  std::string prefix = "CPACK_IFW_COMPONENT_"
+    + cmsys::SystemTools::UpperCase(component->Name)
+    + "_";
+  const char* option = GetOption(prefix + "NAME");
+  name = option ? option : component->Name;
+  if(component->Group)
+    {
+    cmCPackIFWPackage* package = GetGroupPackage(component->Group);
+    if((componentPackageMethod == ONE_PACKAGE_PER_GROUP)
+       || IsOn(prefix + "COMMON"))
+      {
+      return package->Name;
+      }
+    bool dot = !ResolveDuplicateNames;
+    if(dot && name.substr(0, package->Name.size()) == package->Name)
+      {
+      dot = false;
+      }
+    if(dot)
+      {
+      name = package->Name + "." + name;
+      }
+    }
+  return name;
+}
+
+//----------------------------------------------------------------------------
+cmCPackIFWPackage* cmCPackIFWGenerator::GetGroupPackage(
+  cmCPackComponentGroup *group) const
+{
+  std::map<cmCPackComponentGroup*, cmCPackIFWPackage*>::const_iterator pit
+    = GroupPackages.find(group);
+  return pit != GroupPackages.end() ? pit->second : 0;
+}
+
+//----------------------------------------------------------------------------
+cmCPackIFWPackage* cmCPackIFWGenerator::GetComponentPackage(
+  cmCPackComponent *component) const
+{
+  std::map<cmCPackComponent*, cmCPackIFWPackage*>::const_iterator pit
+    = ComponentPackages.find(component);
+  return pit != ComponentPackages.end() ? pit->second : 0;
+}
diff --git a/Source/CPack/IFW/cmCPackIFWGenerator.h b/Source/CPack/IFW/cmCPackIFWGenerator.h
new file mode 100644
index 0000000..1d4d67b
--- /dev/null
+++ b/Source/CPack/IFW/cmCPackIFWGenerator.h
@@ -0,0 +1,135 @@
+/*============================================================================
+  CMake - Cross Platform Makefile Generator
+  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
+
+  Distributed under the OSI-approved BSD License (the "License");
+  see accompanying file Copyright.txt for details.
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the License for more information.
+============================================================================*/
+
+#ifndef cmCPackIFWGenerator_h
+#define cmCPackIFWGenerator_h
+
+#include <CPack/cmCPackGenerator.h>
+
+#include "cmCPackIFWPackage.h"
+#include "cmCPackIFWInstaller.h"
+
+/** \class cmCPackIFWGenerator
+ * \brief A generator for Qt Installer Framework tools
+ *
+ * http://qt-project.org/doc/qtinstallerframework/index.html
+ */
+class cmCPackIFWGenerator : public cmCPackGenerator
+{
+public:
+  cmCPackTypeMacro(cmCPackIFWGenerator, cmCPackGenerator);
+
+  typedef std::map<std::string, cmCPackIFWPackage> PackagesMap;
+  typedef std::map<std::string, cmCPackComponent> ComponentsMap;
+  typedef std::map<std::string, cmCPackComponentGroup> ComponentGoupsMap;
+  typedef std::map<std::string, cmCPackIFWPackage::DependenceStruct>
+    DependenceMap;
+
+  /**
+   * Construct IFW generator
+   */
+  cmCPackIFWGenerator();
+
+  /**
+   * Destruct IFW generator
+   */
+  virtual ~cmCPackIFWGenerator();
+
+protected: // cmCPackGenerator reimplementation
+
+  /**
+   * @brief Initialize generator
+   * @return 0 on failure
+   */
+  virtual int InitializeInternal();
+  virtual int PackageFiles();
+  virtual const char* GetPackagingInstallPrefix();
+
+  /**
+   * @brief Extension of binary installer
+   * @return Executable suffix or value from default implementation
+   */
+  virtual const char* GetOutputExtension();
+
+  virtual std::string GetComponentInstallDirNameSuffix(
+    const std::string& componentName);
+
+  /**
+   * @brief Get Component
+   * @param projectName Project name
+   * @param componentName Component name
+   *
+   * This method calls the base implementation.
+   *
+   * @return Pointer to component
+   */
+  virtual cmCPackComponent* GetComponent(
+    const std::string& projectName,
+    const std::string& componentName);
+
+  /**
+   * @brief Get group of component
+   * @param projectName Project name
+   * @param groupName Component group name
+   *
+   * This method calls the base implementation.
+   *
+   * @return Pointer to component group
+   */
+  virtual cmCPackComponentGroup* GetComponentGroup(
+    const std::string& projectName,
+    const std::string& groupName);
+
+  enum cmCPackGenerator::CPackSetDestdirSupport SupportsSetDestdir() const;
+  virtual bool SupportsAbsoluteDestination() const;
+  virtual bool SupportsComponentInstallation() const;
+
+protected: // Methods
+
+  bool IsOnePackage() const;
+
+  std::string GetRootPackageName();
+
+  std::string GetGroupPackageName(cmCPackComponentGroup *group) const;
+  std::string GetComponentPackageName(cmCPackComponent *component) const;
+
+  cmCPackIFWPackage* GetGroupPackage(cmCPackComponentGroup *group) const;
+  cmCPackIFWPackage* GetComponentPackage(cmCPackComponent *component) const;
+
+protected: // Data
+
+  friend class cmCPackIFWPackage;
+  friend class cmCPackIFWInstaller;
+
+  // Installer
+  cmCPackIFWInstaller Installer;
+  // Collection of packages
+  PackagesMap Packages;
+  // Collection of binary packages
+  std::set<cmCPackIFWPackage*> BinaryPackages;
+  // Collection of downloaded packages
+  std::set<cmCPackIFWPackage*> DownloadedPackages;
+  // Dependent packages
+  DependenceMap DependentPackages;
+  std::map<cmCPackComponent*, cmCPackIFWPackage*> ComponentPackages;
+  std::map<cmCPackComponentGroup*, cmCPackIFWPackage*> GroupPackages;
+
+private:
+  std::string RepoGen;
+  std::string BinCreator;
+
+  bool OnlineOnly;
+  bool ResolveDuplicateNames;
+  std::vector<std::string> PkgsDirsVector;
+};
+
+#endif
diff --git a/Source/CPack/IFW/cmCPackIFWInstaller.cxx b/Source/CPack/IFW/cmCPackIFWInstaller.cxx
new file mode 100644
index 0000000..0644ecb
--- /dev/null
+++ b/Source/CPack/IFW/cmCPackIFWInstaller.cxx
@@ -0,0 +1,406 @@
+/*============================================================================
+  CMake - Cross Platform Makefile Generator
+  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
+
+  Distributed under the OSI-approved BSD License (the "License");
+  see accompanying file Copyright.txt for details.
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the License for more information.
+============================================================================*/
+
+#include "cmCPackIFWInstaller.h"
+
+#include "cmCPackIFWGenerator.h"
+
+#include <CPack/cmCPackLog.h>
+
+#include <cmGeneratedFileStream.h>
+#include <cmXMLSafe.h>
+
+#ifdef cmCPackLogger
+# undef cmCPackLogger
+#endif
+#define cmCPackLogger(logType, msg)                                     \
+  do {                                                                  \
+  cmOStringStream cmCPackLog_msg;                                       \
+  cmCPackLog_msg << msg;                                                \
+  if(Generator) {                                                       \
+  Generator->Logger->Log(logType, __FILE__, __LINE__,                   \
+                         cmCPackLog_msg.str().c_str());                 \
+  }                                                                     \
+  } while ( 0 )
+
+//----------------------------------------------------------------------------
+cmCPackIFWInstaller::cmCPackIFWInstaller() :
+  Generator(0)
+{
+}
+
+//----------------------------------------------------------------------------
+const char *cmCPackIFWInstaller::GetOption(const std::string &op) const
+{
+  return Generator ? Generator->GetOption(op) : 0;
+}
+
+//----------------------------------------------------------------------------
+bool cmCPackIFWInstaller::IsOn(const std::string &op) const
+{
+  return Generator ? Generator->IsOn(op) : false;
+}
+
+//----------------------------------------------------------------------------
+void cmCPackIFWInstaller::ConfigureFromOptions()
+{
+  // Name;
+  if (const char* optIFW_PACKAGE_NAME =
+      this->GetOption("CPACK_IFW_PACKAGE_NAME"))
+    {
+    Name = optIFW_PACKAGE_NAME;
+    }
+  else if (const char* optPACKAGE_NAME =
+           this->GetOption("CPACK_PACKAGE_NAME"))
+    {
+    Name = optPACKAGE_NAME;
+    }
+  else
+    {
+    Name = "Your package";
+    }
+
+  // Title;
+  if (const char* optIFW_PACKAGE_TITLE =
+      GetOption("CPACK_IFW_PACKAGE_TITLE"))
+    {
+    Title = optIFW_PACKAGE_TITLE;
+    }
+  else if (const char* optPACKAGE_DESCRIPTION_SUMMARY =
+           GetOption("CPACK_PACKAGE_DESCRIPTION_SUMMARY"))
+    {
+    Title = optPACKAGE_DESCRIPTION_SUMMARY;
+    }
+  else
+    {
+    Title = "Your package description";
+    }
+
+  // Version;
+  if (const char* option = GetOption("CPACK_PACKAGE_VERSION"))
+    {
+    Version = option;
+    }
+  else
+    {
+    Version = "1.0.0";
+    }
+
+  // Publisher
+  if(const char* optIFW_PACKAGE_PUBLISHER =
+     GetOption("CPACK_IFW_PACKAGE_PUBLISHER"))
+    {
+    Publisher = optIFW_PACKAGE_PUBLISHER;
+    }
+  else if(const char* optPACKAGE_VENDOR = GetOption("CPACK_PACKAGE_VENDOR"))
+    {
+    Publisher = optPACKAGE_VENDOR;
+    }
+
+  // ProductUrl
+  if(const char* option = GetOption("CPACK_IFW_PRODUCT_URL"))
+    {
+    ProductUrl = option;
+    }
+
+  // ApplicationIcon
+  if(const char* option = GetOption("CPACK_IFW_PACKAGE_ICON"))
+    {
+    if(cmSystemTools::FileExists(option))
+      {
+      InstallerApplicationIcon = option;
+      }
+    else
+      {
+      // TODO: implement warning
+      }
+    }
+
+  // WindowIcon
+  if(const char* option = GetOption("CPACK_IFW_PACKAGE_WINDOW_ICON"))
+    {
+    if(cmSystemTools::FileExists(option))
+      {
+      InstallerWindowIcon = option;
+      }
+    else
+      {
+      // TODO: implement warning
+      }
+    }
+
+  // Logo
+  if(const char* option = GetOption("CPACK_IFW_PACKAGE_LOGO"))
+    {
+    if(cmSystemTools::FileExists(option))
+      {
+      Logo = option;
+      }
+    else
+      {
+      // TODO: implement warning
+      }
+    }
+
+  // Default target directory for installation
+  if (const char* optIFW_TARGET_DIRECTORY =
+      GetOption("CPACK_IFW_TARGET_DIRECTORY"))
+    {
+    TargetDir = optIFW_TARGET_DIRECTORY;
+    }
+  else if (const char *optPACKAGE_INSTALL_DIRECTORY =
+           GetOption("CPACK_PACKAGE_INSTALL_DIRECTORY"))
+    {
+    TargetDir = "@ApplicationsDir@/";
+    TargetDir += optPACKAGE_INSTALL_DIRECTORY;
+    }
+  else
+    {
+    TargetDir = "@RootDir@/usr/local";
+    }
+
+  // Default target directory for installation with administrator rights
+  if (const char* option = GetOption("CPACK_IFW_ADMIN_TARGET_DIRECTORY"))
+    {
+    AdminTargetDir = option;
+    }
+
+  // Repositories
+  Repositories.clear();
+  RepositoryStruct Repo;
+  if (const char *site = this->GetOption("CPACK_DOWNLOAD_SITE"))
+    {
+    Repo.Url = site;
+    Repositories.push_back(Repo);
+    }
+  if(const char *RepoAllStr = this->GetOption("CPACK_IFW_REPOSITORIES_ALL"))
+    {
+    std::vector<std::string> RepoAllVector;
+    cmSystemTools::ExpandListArgument(RepoAllStr,
+                                      RepoAllVector);
+    for(std::vector<std::string>::iterator
+          rit = RepoAllVector.begin(); rit != RepoAllVector.end(); ++rit)
+      {
+        std::string prefix = "CPACK_IFW_REPOSITORY_"
+          + cmsys::SystemTools::UpperCase(*rit)
+          + "_";
+        // Url
+        if (const char* url = GetOption(prefix + "URL"))
+          {
+          Repo.Url = url;
+          }
+        else
+          {
+          Repo.Url = "";
+          }
+        // Enabled
+        if (IsOn(prefix + "DISABLED"))
+          {
+          Repo.Enabled = "0";
+          }
+        else
+          {
+          Repo.Enabled = "";
+          }
+        // Username
+        if (const char* username = GetOption(prefix + "USERNAME"))
+          {
+          Repo.Username = username;
+          }
+        else
+          {
+          Repo.Username = "";
+          }
+        // Password
+        if (const char* password = GetOption(prefix + "PASSWORD"))
+          {
+          Repo.Password = password;
+          }
+        else
+          {
+          Repo.Password = "";
+          }
+        // DisplayName
+        if (const char* displayName = GetOption(prefix + "DISPLAY_NAME"))
+          {
+          Repo.DisplayName = displayName;
+          }
+        else
+          {
+          Repo.DisplayName = "";
+          }
+
+        if(!Repo.Url.empty())
+          {
+          Repositories.push_back(Repo);
+          }
+      }
+    }
+}
+
+//----------------------------------------------------------------------------
+void cmCPackIFWInstaller::GenerateInstallerFile()
+{
+  // Lazy directory initialization
+  if(Directory.empty() && Generator)
+    {
+    Directory = Generator->toplevel;
+    }
+
+  // Output stream
+  cmGeneratedFileStream xout((Directory + "/config/config.xml").data());
+
+  xout << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << std::endl;
+  xout << "<Installer>" << std::endl;
+
+  xout << "    <Name>" << cmXMLSafe(Name).str() << "</Name>" << std::endl;
+
+  xout << "    <Version>" << Version << "</Version>" << std::endl;
+
+  xout << "    <Title>" << cmXMLSafe(Title).str() << "</Title>"
+       << std::endl;
+
+  if(!Publisher.empty())
+    {
+    xout << "    <Publisher>" << cmXMLSafe(Publisher).str()
+         << "</Publisher>" << std::endl;
+    }
+
+  if(!ProductUrl.empty())
+    {
+    xout << "    <ProductUrl>" << ProductUrl << "</ProductUrl>" << std::endl;
+    }
+
+  // ApplicationIcon
+  if(!InstallerApplicationIcon.empty())
+    {
+    std::string name =
+      cmSystemTools::GetFilenameName(InstallerApplicationIcon);
+    std::string path = Directory + "/config/" + name;
+    name = cmSystemTools::GetFilenameWithoutExtension(name);
+    cmsys::SystemTools::CopyFileIfDifferent(
+      InstallerApplicationIcon.data(), path.data());
+    xout << "    <InstallerApplicationIcon>" << name
+         << "</InstallerApplicationIcon>" << std::endl;
+    }
+
+  // WindowIcon
+  if(!InstallerWindowIcon.empty())
+    {
+    std::string name = cmSystemTools::GetFilenameName(InstallerWindowIcon);
+    std::string path = Directory + "/config/" + name;
+    cmsys::SystemTools::CopyFileIfDifferent(
+      InstallerWindowIcon.data(), path.data());
+    xout << "    <InstallerWindowIcon>" << name
+         << "</InstallerWindowIcon>" << std::endl;
+    }
+
+  // Logo
+  if(!Logo.empty())
+    {
+    std::string name = cmSystemTools::GetFilenameName(Logo);
+    std::string path = Directory + "/config/" + name;
+    cmsys::SystemTools::CopyFileIfDifferent(Logo.data(), path.data());
+    xout << "    <Logo>" << name << "</Logo>" << std::endl;
+    }
+
+  if(!TargetDir.empty())
+    {
+    xout << "    <TargetDir>" << TargetDir << "</TargetDir>" << std::endl;
+    }
+
+  if(!AdminTargetDir.empty())
+    {
+    xout << "    <AdminTargetDir>" << AdminTargetDir
+         << "</AdminTargetDir>" << std::endl;
+    }
+
+  // Remote repositories
+  if (!Repositories.empty())
+    {
+    xout << "    <RemoteRepositories>" << std::endl;
+    for(std::vector<RepositoryStruct>::iterator
+        rit = Repositories.begin(); rit != Repositories.end(); ++rit)
+      {
+      xout << "        <Repository>" << std::endl;
+      // Url
+      xout << "            <Url>" << rit->Url
+           << "</Url>" << std::endl;
+      // Enabled
+      if(!rit->Enabled.empty())
+        {
+        xout << "            <Enabled>" << rit->Enabled
+             << "</Enabled>" << std::endl;
+        }
+      // Username
+      if(!rit->Username.empty())
+        {
+        xout << "            <Username>" << rit->Username
+             << "</Username>" << std::endl;
+        }
+      // Password
+      if(!rit->Password.empty())
+        {
+        xout << "            <Password>" << rit->Password
+             << "</Password>" << std::endl;
+        }
+      // DisplayName
+      if(!rit->DisplayName.empty())
+        {
+        xout << "            <DisplayName>" << rit->DisplayName
+             << "</DisplayName>" << std::endl;
+        }
+      xout << "        </Repository>" << std::endl;
+      }
+    xout << "    </RemoteRepositories>" << std::endl;
+    }
+
+  // CPack IFW default policy
+  xout << "    <!-- CPack IFW default policy -->" << std::endl;
+  xout << "    <AllowNonAsciiCharacters>true</AllowNonAsciiCharacters>"
+       << std::endl;
+  xout << "    <AllowSpaceInPath>true</AllowSpaceInPath>" << std::endl;
+
+  xout << "</Installer>" << std::endl;
+}
+
+//----------------------------------------------------------------------------
+void cmCPackIFWInstaller::GeneratePackageFiles()
+{
+  if (Packages.empty() || Generator->IsOnePackage())
+    {
+    // Generate default package
+    cmCPackIFWPackage package;
+    package.Generator = Generator;
+    package.Installer = this;
+    // Check package group
+    if (const char* option = GetOption("CPACK_IFW_PACKAGE_GROUP"))
+      {
+      package.ConfigureFromGroup(option);
+      package.ForcedInstallation = "true";
+      }
+    else
+      {
+      package.ConfigureFromOptions();
+      }
+    package.GeneratePackageFile();
+    return;
+    }
+
+  // Generate packages meta information
+  for(PackagesMap::iterator pit = Packages.begin();
+      pit != Packages.end(); ++pit)
+    {
+    cmCPackIFWPackage* package = pit->second;
+    package->GeneratePackageFile();
+    }
+}
diff --git a/Source/CPack/IFW/cmCPackIFWInstaller.h b/Source/CPack/IFW/cmCPackIFWInstaller.h
new file mode 100644
index 0000000..5824d33
--- /dev/null
+++ b/Source/CPack/IFW/cmCPackIFWInstaller.h
@@ -0,0 +1,95 @@
+/*============================================================================
+  CMake - Cross Platform Makefile Generator
+  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
+
+  Distributed under the OSI-approved BSD License (the "License");
+  see accompanying file Copyright.txt for details.
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the License for more information.
+============================================================================*/
+
+#ifndef cmCPackIFWInstaller_h
+#define cmCPackIFWInstaller_h
+
+#include <cmStandardIncludes.h>
+
+class cmCPackIFWPackage;
+class cmCPackIFWGenerator;
+
+/** \class cmCPackIFWInstaller
+ * \brief A binary installer to be created CPack IFW generator
+ */
+class cmCPackIFWInstaller
+{
+public: // Types
+
+  typedef std::map<std::string, cmCPackIFWPackage*> PackagesMap;
+
+  struct RepositoryStruct
+  {
+    std::string Url;
+    std::string Enabled;
+    std::string Username;
+    std::string Password;
+    std::string DisplayName;
+  };
+
+public: // Constructor
+
+  /**
+   * Construct installer
+   */
+  cmCPackIFWInstaller();
+
+public: // Configuration
+
+  /// Name of the product being installed
+  std::string Name;
+
+  /// Version number of the product being installed
+  std::string Version;
+
+  /// Name of the installer as displayed on the title bar
+  std::string Title;
+
+  /// Publisher of the software (as shown in the Windows Control Panel)
+  std::string Publisher;
+
+  /// URL to a page that contains product information on your web site
+  std::string ProductUrl;
+
+  /// Filename for a custom installer icon
+  std::string InstallerApplicationIcon;
+
+  /// Filename for a custom window icon
+  std::string InstallerWindowIcon;
+
+  /// Filename for a logo
+  std::string Logo;
+
+  /// Default target directory for installation
+  std::string TargetDir;
+
+  /// Default target directory for installation with administrator rights
+  std::string AdminTargetDir;
+
+public: // Internal implementation
+
+  const char* GetOption(const std::string& op) const;
+  bool IsOn(const std::string& op) const;
+
+  void ConfigureFromOptions();
+
+  void GenerateInstallerFile();
+
+  void GeneratePackageFiles();
+
+  cmCPackIFWGenerator* Generator;
+  PackagesMap Packages;
+  std::vector<RepositoryStruct> Repositories;
+  std::string Directory;
+};
+
+#endif // cmCPackIFWInstaller_h
diff --git a/Source/CPack/IFW/cmCPackIFWPackage.cxx b/Source/CPack/IFW/cmCPackIFWPackage.cxx
new file mode 100644
index 0000000..3c45639
--- /dev/null
+++ b/Source/CPack/IFW/cmCPackIFWPackage.cxx
@@ -0,0 +1,540 @@
+/*============================================================================
+  CMake - Cross Platform Makefile Generator
+  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
+
+  Distributed under the OSI-approved BSD License (the "License");
+  see accompanying file Copyright.txt for details.
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the License for more information.
+============================================================================*/
+
+#include "cmCPackIFWPackage.h"
+
+#include "cmCPackIFWGenerator.h"
+
+#include <CPack/cmCPackLog.h>
+
+#include <cmGeneratedFileStream.h>
+#include <cmTimestamp.h>
+
+//----------------------------------------------------------------- Logger ---
+#ifdef cmCPackLogger
+# undef cmCPackLogger
+#endif
+#define cmCPackLogger(logType, msg)                                     \
+  do {                                                                  \
+  cmOStringStream cmCPackLog_msg;                                       \
+  cmCPackLog_msg << msg;                                                \
+  if(Generator) {                                                       \
+  Generator->Logger->Log(logType, __FILE__, __LINE__,                   \
+                         cmCPackLog_msg.str().c_str());                 \
+  }                                                                     \
+  } while ( 0 )
+
+//---------------------------------------------------------- CompareStruct ---
+cmCPackIFWPackage::CompareStruct::CompareStruct() :
+  Type(CompareNone)
+{
+}
+
+//------------------------------------------------------- DependenceStruct ---
+cmCPackIFWPackage::DependenceStruct::DependenceStruct()
+{
+}
+
+//----------------------------------------------------------------------------
+cmCPackIFWPackage::DependenceStruct::DependenceStruct(
+  const std::string &dependence)
+{
+  // Search compare section
+  size_t pos = std::string::npos;
+  if((pos = dependence.find("<=")) != std::string::npos)
+    {
+    Compare.Type = CompareLessOrEqual;
+    Compare.Value = dependence.substr(pos + 2);
+    }
+  else if((pos = dependence.find(">=")) != std::string::npos)
+    {
+    Compare.Type = CompareGreaterOrEqual;
+    Compare.Value = dependence.substr(pos + 2);
+    }
+  else if((pos = dependence.find("<")) != std::string::npos)
+    {
+    Compare.Type = CompareLess;
+    Compare.Value = dependence.substr(pos + 1);
+    }
+  else if((pos = dependence.find("=")) != std::string::npos)
+    {
+    Compare.Type = CompareEqual;
+    Compare.Value = dependence.substr(pos + 1);
+    }
+  else if((pos = dependence.find(">")) != std::string::npos)
+    {
+    Compare.Type = CompareGreater;
+    Compare.Value = dependence.substr(pos + 1);
+    }
+  Name = pos == std::string::npos ? dependence : dependence.substr(0, pos);
+}
+
+//----------------------------------------------------------------------------
+std::string cmCPackIFWPackage::DependenceStruct::NameWithCompare() const
+{
+  if (Compare.Type == CompareNone) return Name;
+
+  std::string result = Name;
+
+  if (Compare.Type == CompareLessOrEqual)
+    {
+    result += "<=";
+    }
+  else if (Compare.Type == CompareGreaterOrEqual)
+    {
+    result += ">=";
+    }
+  else if (Compare.Type == CompareLess)
+    {
+    result += "<";
+    }
+  else if (Compare.Type == CompareEqual)
+    {
+    result += "=";
+    }
+  else if (Compare.Type == CompareGreater)
+    {
+    result += ">";
+    }
+
+  result += Compare.Value;
+
+  return result;
+}
+
+//------------------------------------------------------ cmCPackIFWPackage ---
+cmCPackIFWPackage::cmCPackIFWPackage() :
+  Generator(0),
+  Installer(0)
+{
+}
+
+//----------------------------------------------------------------------------
+const char *cmCPackIFWPackage::GetOption(const std::string &op) const
+{
+  const char *option = Generator ? Generator->GetOption(op) : 0;
+  return option && *option ? option : 0;
+}
+
+//----------------------------------------------------------------------------
+bool cmCPackIFWPackage::IsOn(const std::string &op) const
+{
+  return Generator ? Generator->IsOn(op) : false;
+}
+
+//----------------------------------------------------------------------------
+std::string cmCPackIFWPackage::GetComponentName(cmCPackComponent *component)
+{
+  if (!component) return "";
+  const char* option = GetOption(
+    "CPACK_IFW_COMPONENT_"
+    + cmsys::SystemTools::UpperCase(component->Name)
+    + "_NAME");
+  return option ? option : component->Name;
+}
+
+//----------------------------------------------------------------------------
+void cmCPackIFWPackage::DefaultConfiguration()
+{
+  DisplayName = "";
+  Description = "";
+  Version = "";
+  ReleaseDate = "";
+  Script = "";
+  Licenses.clear();
+  SortingPriority = "";
+  Default = "";
+  Virtual = "";
+  ForcedInstallation = "";
+}
+
+//----------------------------------------------------------------------------
+// Defaul configuration (all in one package)
+int cmCPackIFWPackage::ConfigureFromOptions()
+{
+  // Restore defaul configuration
+  DefaultConfiguration();
+
+  // Name
+  Name = Generator->GetRootPackageName();
+
+  // Display name
+  if (const char *option = this->GetOption("CPACK_PACKAGE_NAME"))
+    {
+    DisplayName = option;
+    }
+  else
+    {
+    DisplayName = "Your package";
+    }
+
+  // Description
+  if (const char* option =
+      this->GetOption("CPACK_PACKAGE_DESCRIPTION_SUMMARY"))
+    {
+    Description = option;
+    }
+  else
+    {
+    Description = "Your package description";
+    }
+
+  // Version
+  if(const char* option = GetOption("CPACK_PACKAGE_VERSION"))
+    {
+    Version = option;
+    }
+  else
+    {
+    Version = "1.0.0";
+    }
+
+  ForcedInstallation = "true";
+
+  return 1;
+}
+
+//----------------------------------------------------------------------------
+int cmCPackIFWPackage::ConfigureFromComponent(cmCPackComponent *component)
+{
+  if(!component) return 0;
+
+  // Restore defaul configuration
+  DefaultConfiguration();
+
+  std::string prefix = "CPACK_IFW_COMPONENT_"
+    + cmsys::SystemTools::UpperCase(component->Name)
+    + "_";
+
+  // Display name
+  DisplayName = component->DisplayName;
+
+  // Description
+  Description = component->Description;
+
+  // Version
+  if(const char* optVERSION = GetOption(prefix + "VERSION"))
+    {
+    Version = optVERSION;
+    }
+  else if(const char* optPACKAGE_VERSION =
+          GetOption("CPACK_PACKAGE_VERSION"))
+    {
+    Version = optPACKAGE_VERSION;
+    }
+  else
+    {
+    Version = "1.0.0";
+    }
+
+  // Script
+  if (const char* option = GetOption(prefix + "SCRIPT"))
+    {
+    Script = option;
+    }
+
+  // CMake dependencies
+  if (!component->Dependencies.empty())
+    {
+    std::vector<cmCPackComponent*>::iterator dit;
+    for(dit = component->Dependencies.begin();
+        dit != component->Dependencies.end();
+        ++dit)
+      {
+      Dependencies.insert(Generator->ComponentPackages[*dit]);
+      }
+    }
+
+  // QtIFW dependencies
+  if(const char* option = this->GetOption(prefix + "DEPENDS"))
+    {
+    std::vector<std::string> deps;
+    cmSystemTools::ExpandListArgument(option,
+                                      deps);
+    for(std::vector<std::string>::iterator
+          dit = deps.begin(); dit != deps.end(); ++dit)
+      {
+      DependenceStruct dep(*dit);
+      if (!Generator->Packages.count(dep.Name))
+        {
+        bool hasDep = Generator->DependentPackages.count(dep.Name) > 0;
+        DependenceStruct &depRef =
+          Generator->DependentPackages[dep.Name];
+        if(!hasDep)
+          {
+          depRef = dep;
+          }
+        AlienDependencies.insert(&depRef);
+        }
+      }
+    }
+
+  // Licenses
+  if (const char* option = this->GetOption(prefix + "LICENSES"))
+    {
+    Licenses.clear();
+    cmSystemTools::ExpandListArgument( option, Licenses );
+    if ( Licenses.size() % 2 != 0 )
+      {
+      cmCPackLogger(cmCPackLog::LOG_WARNING, prefix << "LICENSES"
+        << " should contain pairs of <display_name> and <file_path>."
+        << std::endl);
+      Licenses.clear();
+      }
+    }
+
+  // Priority
+  if(const char* option = this->GetOption(prefix + "PRIORITY"))
+    {
+    SortingPriority = option;
+    }
+
+  // Default
+  Default = component->IsDisabledByDefault ? "false" : "true";
+
+  // Virtual
+  Virtual = component->IsHidden ? "true" : "";
+
+  // ForcedInstallation
+  ForcedInstallation = component->IsRequired ? "true" : "false";
+
+  return 1;
+}
+
+//----------------------------------------------------------------------------
+int
+cmCPackIFWPackage::ConfigureFromGroup(cmCPackComponentGroup *group)
+{
+  if(!group) return 0;
+
+  // Restore defaul configuration
+  DefaultConfiguration();
+
+  std::string prefix = "CPACK_IFW_COMPONENT_GROUP_"
+    + cmsys::SystemTools::UpperCase(group->Name)
+    + "_";
+
+  DisplayName = group->DisplayName;
+  Description = group->Description;
+
+  // Version
+  if(const char* optVERSION = GetOption(prefix + "VERSION"))
+    {
+    Version = optVERSION;
+    }
+  else if(const char* optPACKAGE_VERSION =
+          GetOption("CPACK_PACKAGE_VERSION"))
+    {
+    Version = optPACKAGE_VERSION;
+    }
+  else
+    {
+    Version = "1.0.0";
+    }
+
+  // Script
+  if (const char* option = GetOption(prefix + "SCRIPT"))
+    {
+    Script = option;
+    }
+
+  // Licenses
+  if (const char* option = this->GetOption(prefix + "LICENSES"))
+    {
+    Licenses.clear();
+    cmSystemTools::ExpandListArgument( option, Licenses );
+    if ( Licenses.size() % 2 != 0 )
+      {
+      cmCPackLogger(cmCPackLog::LOG_WARNING, prefix << "LICENSES"
+        << " should contain pairs of <display_name> and <file_path>."
+        << std::endl);
+      Licenses.clear();
+      }
+    }
+
+  // Priority
+  if(const char* option = this->GetOption(prefix + "PRIORITY"))
+    {
+    SortingPriority = option;
+    }
+
+  return 1;
+}
+
+//----------------------------------------------------------------------------
+int cmCPackIFWPackage::ConfigureFromGroup(const std::string &groupName)
+{
+  // Group configuration
+
+  cmCPackComponentGroup group;
+  std::string prefix = "CPACK_COMPONENT_GROUP_"
+      + cmsys::SystemTools::UpperCase(groupName)
+      + "_";
+
+  if (const char *option = GetOption(prefix + "DISPLAY_NAME"))
+    {
+    group.DisplayName = option;
+    }
+  else
+    {
+    group.DisplayName = group.Name;
+    }
+
+  if (const char* option = GetOption(prefix + "DESCRIPTION"))
+    {
+    group.Description = option;
+    }
+  group.IsBold = IsOn(prefix + "BOLD_TITLE");
+  group.IsExpandedByDefault = IsOn(prefix + "EXPANDED");
+
+  // Package configuration
+
+  group.Name = groupName;
+
+  if(Generator)
+    {
+    Name = Generator->GetGroupPackageName(&group);
+    }
+  else
+    {
+    Name = group.Name;
+    }
+
+  return ConfigureFromGroup(&group);
+}
+
+//----------------------------------------------------------------------------
+void cmCPackIFWPackage::GeneratePackageFile()
+{
+  // Lazy directory initialization
+  if (Directory.empty())
+    {
+    if(Installer)
+      {
+      Directory = Installer->Directory + "/packages/" + Name;
+      }
+    else if (Generator)
+      {
+      Directory = Generator->toplevel + "/packages/" + Name;
+      }
+    }
+
+  // Output stream
+  cmGeneratedFileStream xout((Directory + "/meta/package.xml").data());
+
+  xout << "<?xml version=\"1.0\"?>" << std::endl;
+  xout << "<Package>" << std::endl;
+
+  xout << "    <DisplayName>" << DisplayName
+       << "</DisplayName>" << std::endl;
+
+  xout << "    <Description>" << Description
+       << "</Description>" << std::endl;
+
+  xout << "    <Name>" << Name << "</Name>" << std::endl;
+
+  xout << "    <Version>" <<  Version
+       << "</Version>" << std::endl;
+
+  xout << "    <ReleaseDate>";
+  if(ReleaseDate.empty())
+    {
+    xout << cmTimestamp().CurrentTime("%Y-%m-%d", true);
+    }
+  else
+    {
+    xout << ReleaseDate;
+    }
+  xout << "</ReleaseDate>" << std::endl;
+
+  // Script (copy to meta dir)
+  if(!Script.empty())
+    {
+    std::string name = cmSystemTools::GetFilenameName(Script);
+    std::string path = Directory + "/meta/" + name;
+    cmsys::SystemTools::CopyFileIfDifferent(Script.data(), path.data());
+    xout << "    <Script>" << name << "</Script>" << std::endl;
+    }
+
+  // Dependencies
+  std::set<DependenceStruct> compDepSet;
+  for(std::set<DependenceStruct*>::iterator ait = AlienDependencies.begin();
+      ait != AlienDependencies.end(); ++ait)
+    {
+    compDepSet.insert(*(*ait));
+    }
+  for(std::set<cmCPackIFWPackage*>::iterator it = Dependencies.begin();
+      it != Dependencies.end(); ++it)
+    {
+    compDepSet.insert(DependenceStruct((*it)->Name));
+    }
+  // Write dependencies
+  if  (!compDepSet.empty())
+    {
+    xout << "    <Dependencies>";
+    std::set<DependenceStruct>::iterator it = compDepSet.begin();
+    xout << it->NameWithCompare();
+    ++it;
+    while(it != compDepSet.end())
+      {
+      xout << "," << it->NameWithCompare();
+      ++it;
+      }
+    xout << "</Dependencies>" << std::endl;
+    }
+
+  // Licenses (copy to meta dir)
+  std::vector<std::string> licenses = Licenses;
+  for(size_t i = 1; i < licenses.size(); i += 2)
+    {
+    std::string name = cmSystemTools::GetFilenameName(licenses[i]);
+    std::string path = Directory + "/meta/" + name;
+    cmsys::SystemTools::CopyFileIfDifferent(licenses[i].data(), path.data());
+    licenses[i] = name;
+    }
+  if(!licenses.empty())
+    {
+    xout << "    <Licenses>" << std::endl;
+    for(size_t i = 0; i < licenses.size(); i += 2)
+      {
+      xout << "        <License "
+           << "name=\"" << licenses[i] << "\" "
+           << "file=\"" << licenses[i + 1] << "\" "
+           << "/>" <<std::endl;
+      }
+    xout << "    </Licenses>" << std::endl;
+    }
+
+  if (!ForcedInstallation.empty())
+    {
+    xout << "    <ForcedInstallation>" << ForcedInstallation
+         << "</ForcedInstallation>" << std::endl;
+    }
+
+  if (!Virtual.empty())
+    {
+    xout << "    <Virtual>" << Virtual << "</Virtual>" << std::endl;
+    }
+  else if (!Default.empty())
+    {
+    xout << "    <Default>" << Default << "</Default>" << std::endl;
+    }
+
+  // Priority
+  if(!SortingPriority.empty())
+    {
+    xout << "    <SortingPriority>" << SortingPriority
+         << "</SortingPriority>" << std::endl;
+    }
+
+  xout << "</Package>" << std::endl;
+}
diff --git a/Source/CPack/IFW/cmCPackIFWPackage.h b/Source/CPack/IFW/cmCPackIFWPackage.h
new file mode 100644
index 0000000..9fc9bd0
--- /dev/null
+++ b/Source/CPack/IFW/cmCPackIFWPackage.h
@@ -0,0 +1,133 @@
+/*============================================================================
+  CMake - Cross Platform Makefile Generator
+  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
+
+  Distributed under the OSI-approved BSD License (the "License");
+  see accompanying file Copyright.txt for details.
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the License for more information.
+============================================================================*/
+
+#ifndef cmCPackIFWPackage_h
+#define cmCPackIFWPackage_h
+
+#include <cmStandardIncludes.h>
+
+class cmCPackComponent;
+class cmCPackComponentGroup;
+class cmCPackIFWInstaller;
+class cmCPackIFWGenerator;
+
+/** \class cmCPackIFWPackage
+ * \brief A single component to be installed by CPack IFW generator
+ */
+class cmCPackIFWPackage
+{
+public: // Types
+  enum CompareTypes
+  {
+    CompareNone           = 0x0,
+    CompareEqual          = 0x1,
+    CompareLess           = 0x2,
+    CompareLessOrEqual    = 0x3,
+    CompareGreater        = 0x4,
+    CompareGreaterOrEqual = 0x5
+  };
+
+  struct CompareStruct
+  {
+    CompareStruct();
+
+    unsigned int Type;
+    std::string Value;
+  };
+
+  struct DependenceStruct
+  {
+    DependenceStruct();
+    DependenceStruct(const std::string &dependence);
+
+    std::string Name;
+    CompareStruct Compare;
+
+    std::string NameWithCompare() const;
+
+    bool operator < (const DependenceStruct &other) const
+      {
+      return Name < other.Name;
+      }
+  };
+
+public: // [Con|De]structor
+
+  /**
+   * Construct package
+   */
+  cmCPackIFWPackage();
+
+public: // Configuration
+
+  /// Human-readable name of the component
+  std::string DisplayName;
+
+  /// Human-readable description of the component
+  std::string Description;
+
+  /// Version number of the component
+  std::string Version;
+
+  /// Date when this component version was released
+  std::string ReleaseDate;
+
+  /// Domain-like identification for this component
+  std::string Name;
+
+  /// File name of a script being loaded
+  std::string Script;
+
+  /// List of license agreements to be accepted by the installing user
+  std::vector<std::string> Licenses;
+
+  /// Priority of the component in the tree
+  std::string SortingPriority;
+
+  /// Set to true to preselect the component in the installer
+  std::string Default;
+
+  /// Set to true to hide the component from the installer
+  std::string Virtual;
+
+  /// Determines that the package must always be installed
+  std::string ForcedInstallation;
+
+public: // Internal implementation
+
+  const char* GetOption(const std::string& op) const;
+  bool IsOn(const std::string& op) const;
+
+  std::string GetComponentName(cmCPackComponent *component);
+
+  void DefaultConfiguration();
+
+  int ConfigureFromOptions();
+  int ConfigureFromComponent(cmCPackComponent *component);
+  int ConfigureFromGroup(cmCPackComponentGroup *group);
+  int ConfigureFromGroup(const std::string &groupName);
+
+  void GeneratePackageFile();
+
+  // Pointer to generator
+  cmCPackIFWGenerator* Generator;
+  // Pointer to installer
+  cmCPackIFWInstaller* Installer;
+  // Collection of dependencies
+  std::set<cmCPackIFWPackage*> Dependencies;
+  // Collection of unresolved dependencies
+  std::set<DependenceStruct*> AlienDependencies;
+  // Patch to package directory
+  std::string Directory;
+};
+
+#endif // cmCPackIFWPackage_h
diff --git a/Source/CPack/WiX/cmCPackWIXGenerator.cxx b/Source/CPack/WiX/cmCPackWIXGenerator.cxx
index a2995d1..7e00027 100644
--- a/Source/CPack/WiX/cmCPackWIXGenerator.cxx
+++ b/Source/CPack/WiX/cmCPackWIXGenerator.cxx
@@ -360,6 +360,29 @@
       includeFile.EndElement("Property");
       }
     }
+
+  if(GetOption("CPACK_WIX_PROPERTY_ARPINSTALLLOCATION") == 0)
+    {
+    includeFile.BeginElement("Property");
+    includeFile.AddAttribute("Id", "INSTALL_ROOT");
+    includeFile.AddAttribute("Secure", "yes");
+
+    includeFile.BeginElement("RegistrySearch");
+    includeFile.AddAttribute("Id", "FindInstallLocation");
+    includeFile.AddAttribute("Root", "HKLM");
+    includeFile.AddAttribute("Key", "Software\\Microsoft\\Windows\\"
+      "CurrentVersion\\Uninstall\\[WIX_UPGRADE_DETECTED]");
+    includeFile.AddAttribute("Name", "InstallLocation");
+    includeFile.AddAttribute("Type", "raw");
+    includeFile.EndElement("RegistrySearch");
+    includeFile.EndElement("Property");
+
+    includeFile.BeginElement("SetProperty");
+    includeFile.AddAttribute("Id", "ARPINSTALLLOCATION");
+    includeFile.AddAttribute("Value", "[INSTALL_ROOT]");
+    includeFile.AddAttribute("After", "CostFinalize");
+    includeFile.EndElement("SetProperty");
+    }
 }
 
 void cmCPackWIXGenerator::CopyDefinition(
@@ -824,13 +847,42 @@
   cmsys::Directory dir;
   dir.Load(topdir.c_str());
 
-  if(dir.GetNumberOfFiles() == 2)
+  std::string relativeDirectoryPath =
+    cmSystemTools::RelativePath(toplevel.c_str(), topdir.c_str());
+
+  if(relativeDirectoryPath.empty())
+    {
+    relativeDirectoryPath = ".";
+    }
+
+  cmInstalledFile const* directoryInstalledFile =
+    this->GetInstalledFile(relativeDirectoryPath);
+
+  bool emptyDirectory = dir.GetNumberOfFiles() == 2;
+  bool createDirectory = false;
+
+  if(emptyDirectory)
+    {
+    createDirectory = true;
+    }
+
+  if(directoryInstalledFile)
+    {
+    if(directoryInstalledFile->HasProperty("CPACK_WIX_ACL"))
+      {
+      createDirectory = true;
+      }
+    }
+
+  if(createDirectory)
     {
     std::string componentId = fileDefinitions.EmitComponentCreateFolder(
-      directoryId, GenerateGUID());
-
+      directoryId, GenerateGUID(), directoryInstalledFile);
     featureDefinitions.EmitComponentRef(componentId);
+    }
 
+  if(emptyDirectory)
+    {
     return;
     }
 
diff --git a/Source/CPack/WiX/cmWIXAccessControlList.cxx b/Source/CPack/WiX/cmWIXAccessControlList.cxx
new file mode 100644
index 0000000..aeec968
--- /dev/null
+++ b/Source/CPack/WiX/cmWIXAccessControlList.cxx
@@ -0,0 +1,149 @@
+/*============================================================================
+  CMake - Cross Platform Makefile Generator
+  Copyright 2014 Kitware, Inc.
+
+  Distributed under the OSI-approved BSD License (the "License");
+  see accompanying file Copyright.txt for details.
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the License for more information.
+============================================================================*/
+
+#include "cmWIXAccessControlList.h"
+
+#include <CPack/cmCPackGenerator.h>
+
+#include <cmSystemTools.h>
+
+cmWIXAccessControlList::cmWIXAccessControlList(
+      cmCPackLog *logger,
+      cmInstalledFile const& installedFile,
+      cmWIXSourceWriter &sourceWriter):
+        Logger(logger),
+        InstalledFile(installedFile),
+        SourceWriter(sourceWriter)
+{
+
+}
+
+bool cmWIXAccessControlList::Apply()
+{
+  std::vector<std::string> entries;
+  this->InstalledFile.GetPropertyAsList("CPACK_WIX_ACL", entries);
+
+  for(size_t i = 0; i < entries.size(); ++i)
+    {
+    this->CreatePermissionElement(entries[i]);
+    }
+
+  return true;
+}
+
+void cmWIXAccessControlList::CreatePermissionElement(
+  std::string const& entry)
+{
+  std::string::size_type pos = entry.find('=');
+  if(pos == std::string::npos)
+    {
+    this->ReportError(entry, "Did not find mandatory '='");
+    return;
+    }
+
+  std::string user_and_domain = entry.substr(0, pos);
+  std::string permission_string = entry.substr(pos + 1);
+
+  pos = user_and_domain.find('@');
+  std::string user;
+  std::string domain;
+  if(pos != std::string::npos)
+    {
+    user = user_and_domain.substr(0, pos);
+    domain = user_and_domain.substr(pos + 1);
+    }
+  else
+    {
+    user = user_and_domain;
+    }
+
+  std::vector<std::string> permissions =
+    cmSystemTools::tokenize(permission_string, ",");
+
+  this->SourceWriter.BeginElement("Permission");
+  this->SourceWriter.AddAttribute("User", user);
+  if(domain.size())
+    {
+    this->SourceWriter.AddAttribute("Domain", domain);
+    }
+  for(size_t i = 0; i < permissions.size(); ++i)
+    {
+    this->EmitBooleanAttribute(entry,
+      cmSystemTools::TrimWhitespace(permissions[i]));
+    }
+  this->SourceWriter.EndElement("Permission");
+}
+
+void cmWIXAccessControlList::ReportError(
+  std::string const& entry,
+  std::string const& message)
+{
+  cmCPackLogger(cmCPackLog::LOG_ERROR,
+    "Failed processing ACL entry '" << entry <<
+    "': " << message << std::endl);
+}
+
+bool cmWIXAccessControlList::IsBooleanAttribute(std::string const& name)
+{
+  static const char* validAttributes[] =
+  {
+    "Append",
+    "ChangePermission",
+    "CreateChild",
+    "CreateFile",
+    "CreateLink",
+    "CreateSubkeys",
+    "Delete",
+    "DeleteChild",
+    "EnumerateSubkeys",
+    "Execute",
+    "FileAllRights",
+    "GenericAll",
+    "GenericExecute",
+    "GenericRead",
+    "GenericWrite",
+    "Notify",
+    "Read",
+    "ReadAttributes",
+    "ReadExtendedAttributes",
+    "ReadPermission",
+    "SpecificRightsAll",
+    "Synchronize",
+    "TakeOwnership",
+    "Traverse",
+    "Write",
+    "WriteAttributes",
+    "WriteExtendedAttributes",
+    0
+  };
+
+  size_t i = 0;
+  while(validAttributes[i])
+    {
+    if(name == validAttributes[i++]) return true;
+    }
+
+  return false;
+}
+
+void cmWIXAccessControlList::EmitBooleanAttribute(
+  std::string const& entry, std::string const& name)
+{
+  if(!this->IsBooleanAttribute(name))
+    {
+    std::stringstream message;
+    message << "Unknown boolean attribute '" << name << "'";
+    this->ReportError(entry, message.str());
+    }
+
+  this->SourceWriter.AddAttribute(name, "yes");
+}
diff --git a/Source/CPack/WiX/cmWIXAccessControlList.h b/Source/CPack/WiX/cmWIXAccessControlList.h
new file mode 100644
index 0000000..20902f7
--- /dev/null
+++ b/Source/CPack/WiX/cmWIXAccessControlList.h
@@ -0,0 +1,46 @@
+/*============================================================================
+  CMake - Cross Platform Makefile Generator
+  Copyright 2014 Kitware, Inc.
+
+  Distributed under the OSI-approved BSD License (the "License");
+  see accompanying file Copyright.txt for details.
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the License for more information.
+============================================================================*/
+
+#ifndef cmWIXAccessControlList_h
+#define cmWIXAccessControlList_h
+
+#include <cmInstalledFile.h>
+#include <CPack/cmCPackLog.h>
+
+#include "cmWIXSourceWriter.h"
+
+class cmWIXAccessControlList
+{
+public:
+  cmWIXAccessControlList(
+        cmCPackLog *logger,
+        cmInstalledFile const& installedFile,
+        cmWIXSourceWriter &sourceWriter);
+
+  bool Apply();
+
+private:
+  void CreatePermissionElement(std::string const& entry);
+
+  void ReportError(std::string const& entry, std::string const& message);
+
+  bool IsBooleanAttribute(std::string const& name);
+
+  void EmitBooleanAttribute(
+    std::string const& entry, std::string const& name);
+
+  cmCPackLog* Logger;
+  cmInstalledFile const& InstalledFile;
+  cmWIXSourceWriter &SourceWriter;
+};
+
+#endif
diff --git a/Source/CPack/WiX/cmWIXFilesSourceWriter.cxx b/Source/CPack/WiX/cmWIXFilesSourceWriter.cxx
index 451188e..1adb06a 100644
--- a/Source/CPack/WiX/cmWIXFilesSourceWriter.cxx
+++ b/Source/CPack/WiX/cmWIXFilesSourceWriter.cxx
@@ -11,6 +11,7 @@
 ============================================================================*/
 
 #include "cmWIXFilesSourceWriter.h"
+#include "cmWIXAccessControlList.h"
 
 #include <cmInstalledFile.h>
 
@@ -112,7 +113,9 @@
 }
 
 std::string cmWIXFilesSourceWriter::EmitComponentCreateFolder(
-  std::string const& directoryId, std::string const& guid)
+  std::string const& directoryId,
+  std::string const& guid,
+  cmInstalledFile const* installedFile)
 {
   std::string componentId =
     std::string("CM_C_EMPTY_") + directoryId;
@@ -126,6 +129,12 @@
 
   BeginElement("CreateFolder");
 
+  if(installedFile)
+    {
+    cmWIXAccessControlList acl(Logger, *installedFile, *this);
+    acl.Apply();
+    }
+
   EndElement("CreateFolder");
   EndElement("Component");
   EndElement("DirectoryRef");
@@ -175,6 +184,12 @@
     AddAttribute("ReadOnly", "yes");
     }
 
+  if(installedFile)
+    {
+    cmWIXAccessControlList acl(Logger, *installedFile, *this);
+    acl.Apply();
+    }
+
   patch.ApplyFragment(fileId, *this);
   EndElement("File");
 
diff --git a/Source/CPack/WiX/cmWIXFilesSourceWriter.h b/Source/CPack/WiX/cmWIXFilesSourceWriter.h
index 23ef561..b0a4af8 100644
--- a/Source/CPack/WiX/cmWIXFilesSourceWriter.h
+++ b/Source/CPack/WiX/cmWIXFilesSourceWriter.h
@@ -47,7 +47,8 @@
 
   std::string EmitComponentCreateFolder(
     std::string const& directoryId,
-    std::string const& guid);
+    std::string const& guid,
+    cmInstalledFile const* installedFile);
 
   std::string EmitComponentFile(
     std::string const& directoryId,
diff --git a/Source/CPack/WiX/cmWIXSourceWriter.h b/Source/CPack/WiX/cmWIXSourceWriter.h
index 65b7240..3957d96 100644
--- a/Source/CPack/WiX/cmWIXSourceWriter.h
+++ b/Source/CPack/WiX/cmWIXSourceWriter.h
@@ -45,6 +45,9 @@
 
   static std::string WindowsCodepageToUtf8(std::string const& value);
 
+protected:
+   cmCPackLog* Logger;
+
 private:
   enum State
   {
@@ -58,8 +61,6 @@
 
   static std::string EscapeAttributeValue(std::string const& value);
 
-  cmCPackLog* Logger;
-
   cmsys::ofstream File;
 
   State State;
diff --git a/Source/CPack/cmCPack7zGenerator.cxx b/Source/CPack/cmCPack7zGenerator.cxx
new file mode 100644
index 0000000..ce31ad4
--- /dev/null
+++ b/Source/CPack/cmCPack7zGenerator.cxx
@@ -0,0 +1,25 @@
+/*============================================================================
+  CMake - Cross Platform Makefile Generator
+  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
+
+  Distributed under the OSI-approved BSD License (the "License");
+  see accompanying file Copyright.txt for details.
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the License for more information.
+============================================================================*/
+
+#include "cmCPack7zGenerator.h"
+
+//----------------------------------------------------------------------
+cmCPack7zGenerator::cmCPack7zGenerator()
+  :cmCPackArchiveGenerator(cmArchiveWrite::CompressNone,
+                           cmArchiveWrite::Type7Zip)
+{
+}
+
+//----------------------------------------------------------------------
+cmCPack7zGenerator::~cmCPack7zGenerator()
+{
+}
diff --git a/Source/CPack/cmCPack7zGenerator.h b/Source/CPack/cmCPack7zGenerator.h
new file mode 100644
index 0000000..f5a323f
--- /dev/null
+++ b/Source/CPack/cmCPack7zGenerator.h
@@ -0,0 +1,36 @@
+/*============================================================================
+  CMake - Cross Platform Makefile Generator
+  Copyright 2000-2009 Kitware, Inc.
+
+  Distributed under the OSI-approved BSD License (the "License");
+  see accompanying file Copyright.txt for details.
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the License for more information.
+============================================================================*/
+
+#ifndef cmCPack7zGenerator_h
+#define cmCPack7zGenerator_h
+
+#include "cmCPackArchiveGenerator.h"
+
+/** \class cmCPack7zGenerator
+ * \brief A generator for 7z files
+ */
+class cmCPack7zGenerator : public cmCPackArchiveGenerator
+{
+public:
+  cmCPackTypeMacro(cmCPack7zGenerator, cmCPackArchiveGenerator);
+
+  /**
+   * Construct generator
+   */
+  cmCPack7zGenerator();
+  virtual ~cmCPack7zGenerator();
+
+protected:
+  virtual const char* GetOutputExtension() { return ".7z"; }
+};
+
+#endif
diff --git a/Source/CPack/cmCPackGenerator.cxx b/Source/CPack/cmCPackGenerator.cxx
index 91f92c5..1461bb1 100644
--- a/Source/CPack/cmCPackGenerator.cxx
+++ b/Source/CPack/cmCPackGenerator.cxx
@@ -637,8 +637,8 @@
       if ( globalGenerator->GetPreinstallTargetName() )
         {
         globalGenerator->FindMakeProgram(this->MakefileMap);
-        const char* cmakeMakeProgram
-          = this->MakefileMap->GetDefinition("CMAKE_MAKE_PROGRAM");
+        std::string cmakeMakeProgram
+          = this->MakefileMap->GetSafeDefinition("CMAKE_MAKE_PROGRAM");
         std::vector<std::string> buildCommand;
         globalGenerator->GenerateBuildCommand(buildCommand, cmakeMakeProgram,
             installProjectName, installDirectory,
@@ -1049,7 +1049,6 @@
 
   const char* tempPackageFileName = this->GetOption(
     "CPACK_TEMPORARY_PACKAGE_FILE_NAME");
-  const char* packageFileName = this->GetOption("CPACK_OUTPUT_FILE_PATH");
   const char* tempDirectory = this->GetOption("CPACK_TEMPORARY_DIRECTORY");
 
   cmCPackLogger(cmCPackLog::LOG_DEBUG, "Find files" << std::endl);
@@ -1114,7 +1113,7 @@
     std::string tmpPF(this->GetOption("CPACK_OUTPUT_FILE_PREFIX"));
     tempPackageFileName = it->c_str();
     tmpPF += "/"+cmSystemTools::GetFilenameName(*it);
-    packageFileName = tmpPF.c_str();
+    const char* packageFileName = tmpPF.c_str();
     cmCPackLogger(cmCPackLog::LOG_DEBUG, "Copy final package(s): "
         << (tempPackageFileName ? tempPackageFileName : "(NULL)" )
         << " to "
diff --git a/Source/CPack/cmCPackGeneratorFactory.cxx b/Source/CPack/cmCPackGeneratorFactory.cxx
index 9faf2b0..c8737f4 100644
--- a/Source/CPack/cmCPackGeneratorFactory.cxx
+++ b/Source/CPack/cmCPackGeneratorFactory.cxx
@@ -14,11 +14,14 @@
 
 #include "cmCPackGenerator.h"
 #include "cmCPackTGZGenerator.h"
+#include "cmCPackTXZGenerator.h"
 #include "cmCPackTarBZip2Generator.h"
 #include "cmCPackTarCompressGenerator.h"
 #include "cmCPackZIPGenerator.h"
+#include "cmCPack7zGenerator.h"
 #include "cmCPackSTGZGenerator.h"
 #include "cmCPackNSISGenerator.h"
+#include "IFW/cmCPackIFWGenerator.h"
 
 #ifdef __APPLE__
 #  include "cmCPackDragNDropGenerator.h"
@@ -56,6 +59,11 @@
     this->RegisterGenerator("TGZ", "Tar GZip compression",
       cmCPackTGZGenerator::CreateGenerator);
     }
+  if (cmCPackTXZGenerator::CanGenerate())
+    {
+    this->RegisterGenerator("TXZ", "Tar XZ compression",
+      cmCPackTXZGenerator::CreateGenerator);
+    }
   if (cmCPackSTGZGenerator::CanGenerate())
     {
     this->RegisterGenerator("STGZ", "Self extracting Tar GZip compression",
@@ -68,6 +76,11 @@
     this->RegisterGenerator("NSIS64", "Null Soft Installer (64-bit)",
       cmCPackNSISGenerator::CreateGenerator64);
     }
+  if (cmCPackIFWGenerator::CanGenerate())
+    {
+    this->RegisterGenerator("IFW", "Qt Installer Framework",
+      cmCPackIFWGenerator::CreateGenerator);
+    }
 #ifdef __CYGWIN__
   if (cmCPackCygwinBinaryGenerator::CanGenerate())
     {
@@ -86,6 +99,11 @@
     this->RegisterGenerator("ZIP", "ZIP file format",
       cmCPackZIPGenerator::CreateGenerator);
     }
+  if (cmCPack7zGenerator::CanGenerate())
+    {
+    this->RegisterGenerator("7Z", "7-Zip file format",
+      cmCPack7zGenerator::CreateGenerator);
+    }
 #ifdef _WIN32
   if (cmCPackWIXGenerator::CanGenerate())
     {
diff --git a/Source/CPack/cmCPackNSISGenerator.cxx b/Source/CPack/cmCPackNSISGenerator.cxx
index 0113698..a5eee6b 100644
--- a/Source/CPack/cmCPackNSISGenerator.cxx
+++ b/Source/CPack/cmCPackNSISGenerator.cxx
@@ -588,8 +588,8 @@
     return;
     }
 
-  cmsys::RegularExpression urlRegex;
-  urlRegex.compile("^(mailto:|(ftps?|https?|news)://).*$");
+  static cmsys::RegularExpression
+    urlRegex("^(mailto:|(ftps?|https?|news)://).*$");
 
   std::vector<std::string>::iterator it;
   for ( it = cpackMenuLinksVector.begin();
diff --git a/Source/CPack/cmCPackTXZGenerator.cxx b/Source/CPack/cmCPackTXZGenerator.cxx
new file mode 100644
index 0000000..ecfc177
--- /dev/null
+++ b/Source/CPack/cmCPackTXZGenerator.cxx
@@ -0,0 +1,25 @@
+/*============================================================================
+  CMake - Cross Platform Makefile Generator
+  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
+
+  Distributed under the OSI-approved BSD License (the "License");
+  see accompanying file Copyright.txt for details.
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the License for more information.
+============================================================================*/
+
+#include "cmCPackTXZGenerator.h"
+
+//----------------------------------------------------------------------
+cmCPackTXZGenerator::cmCPackTXZGenerator()
+  :cmCPackArchiveGenerator(cmArchiveWrite::CompressXZ,
+                           cmArchiveWrite::TypeTAR)
+{
+}
+
+//----------------------------------------------------------------------
+cmCPackTXZGenerator::~cmCPackTXZGenerator()
+{
+}
diff --git a/Source/CPack/cmCPackTXZGenerator.h b/Source/CPack/cmCPackTXZGenerator.h
new file mode 100644
index 0000000..bf8152f
--- /dev/null
+++ b/Source/CPack/cmCPackTXZGenerator.h
@@ -0,0 +1,35 @@
+/*============================================================================
+  CMake - Cross Platform Makefile Generator
+  Copyright 2000-2009 Kitware, Inc.
+
+  Distributed under the OSI-approved BSD License (the "License");
+  see accompanying file Copyright.txt for details.
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the License for more information.
+============================================================================*/
+
+#ifndef cmCPackTXZGenerator_h
+#define cmCPackTXZGenerator_h
+
+#include "cmCPackArchiveGenerator.h"
+
+/** \class cmCPackTXZGenerator
+ * \brief A generator for TXZ files
+ *
+ */
+class cmCPackTXZGenerator : public cmCPackArchiveGenerator
+{
+public:
+  cmCPackTypeMacro(cmCPackTXZGenerator, cmCPackArchiveGenerator);
+  /**
+   * Construct generator
+   */
+  cmCPackTXZGenerator();
+  virtual ~cmCPackTXZGenerator();
+protected:
+  virtual const char* GetOutputExtension() { return ".tar.xz"; }
+};
+
+#endif
diff --git a/Source/CPack/cpack.cxx b/Source/CPack/cpack.cxx
index ad37c42..c57028d 100644
--- a/Source/CPack/cpack.cxx
+++ b/Source/CPack/cpack.cxx
@@ -101,7 +101,7 @@
 // this is CPack.
 int main (int argc, char const* const* argv)
 {
-  setlocale(LC_ALL, "");
+  setlocale(LC_CTYPE, "");
   cmsys::Encoding::CommandLineArguments args =
     cmsys::Encoding::CommandLineArguments::Main(argc, argv);
   argc = args.argc();
@@ -343,7 +343,6 @@
       {
       cmCPack_Log(&log, cmCPackLog::LOG_ERROR,
         "CPack generator not specified" << std::endl);
-      parsed = 0;
       }
     else
       {
diff --git a/Source/CTest/cmCTestBatchTestHandler.cxx b/Source/CTest/cmCTestBatchTestHandler.cxx
index 934481b..7f966aa 100644
--- a/Source/CTest/cmCTestBatchTestHandler.cxx
+++ b/Source/CTest/cmCTestBatchTestHandler.cxx
@@ -33,8 +33,8 @@
 {
   this->Script = this->CTest->GetBinaryDir()
     + "/Testing/CTestBatch.txt";
-  std::fstream fout;
-  fout.open(this->Script.c_str(), std::ios::out);
+  cmsys::ofstream fout;
+  fout.open(this->Script.c_str());
   fout << "#!/bin/sh\n";
 
   for(TestMap::iterator i = this->Tests.begin(); i != this->Tests.end(); ++i)
@@ -48,7 +48,7 @@
 }
 
 //---------------------------------------------------------
-void cmCTestBatchTestHandler::WriteSrunArgs(int test, std::fstream& fout)
+void cmCTestBatchTestHandler::WriteSrunArgs(int test, cmsys::ofstream& fout)
 {
   cmCTestTestHandler::cmCTestTestProperties* properties =
       this->Properties[test];
@@ -79,7 +79,7 @@
 }
 
 //---------------------------------------------------------
-void cmCTestBatchTestHandler::WriteTestCommand(int test, std::fstream& fout)
+void cmCTestBatchTestHandler::WriteTestCommand(int test, cmsys::ofstream& fout)
 {
   std::vector<std::string> args = this->Properties[test]->Args;
   std::vector<std::string> processArgs;
diff --git a/Source/CTest/cmCTestBatchTestHandler.h b/Source/CTest/cmCTestBatchTestHandler.h
index ab0d081..e0c6e48 100644
--- a/Source/CTest/cmCTestBatchTestHandler.h
+++ b/Source/CTest/cmCTestBatchTestHandler.h
@@ -17,6 +17,7 @@
 #include <cmCTestTestHandler.h>
 #include <cmCTestMultiProcessHandler.h>
 #include <cmCTestRunTest.h>
+#include <cmsys/FStream.hxx>
 
 /** \class cmCTestBatchTestHandler
  * \brief run parallel ctest
@@ -30,8 +31,8 @@
   virtual void RunTests();
 protected:
   void WriteBatchScript();
-  void WriteSrunArgs(int test, std::fstream& fout);
-  void WriteTestCommand(int test, std::fstream& fout);
+  void WriteSrunArgs(int test, cmsys::ofstream& fout);
+  void WriteTestCommand(int test, cmsys::ofstream& fout);
 
   void SubmitBatchScript();
 
diff --git a/Source/CTest/cmCTestBuildAndTestHandler.cxx b/Source/CTest/cmCTestBuildAndTestHandler.cxx
index b4818be..41db042 100644
--- a/Source/CTest/cmCTestBuildAndTestHandler.cxx
+++ b/Source/CTest/cmCTestBuildAndTestHandler.cxx
@@ -68,6 +68,12 @@
     generator += this->BuildGenerator;
     args.push_back(generator);
     }
+  if(!this->BuildGeneratorPlatform.empty())
+    {
+    std::string platform = "-A";
+    platform += this->BuildGeneratorPlatform;
+    args.push_back(platform);
+    }
   if(this->BuildGeneratorToolset.size())
     {
     std::string toolset = "-T";
@@ -246,6 +252,7 @@
     // Make the generator available for the Build call below.
     cm.SetGlobalGenerator(cm.CreateGlobalGenerator(
                             this->BuildGenerator));
+    cm.SetGeneratorPlatform(this->BuildGeneratorPlatform);
     cm.SetGeneratorToolset(this->BuildGeneratorToolset);
 
     // Load the cache to make CMAKE_MAKE_PROGRAM available.
@@ -301,7 +308,7 @@
     int retVal = cm.GetGlobalGenerator()->Build(
       this->SourceDir, this->BinaryDir,
       this->BuildProject, *tarIt,
-      &output, this->BuildMakeProgram,
+      output, this->BuildMakeProgram,
       config,
       !this->BuildNoClean,
       false, remainingTime);
@@ -490,6 +497,12 @@
     idx++;
     this->BuildGenerator = allArgs[idx];
     }
+  if(currentArg == "--build-generator-platform" &&
+     idx < allArgs.size() - 1)
+    {
+    idx++;
+    this->BuildGeneratorPlatform = allArgs[idx];
+    }
   if(currentArg == "--build-generator-toolset" &&
      idx < allArgs.size() - 1)
     {
diff --git a/Source/CTest/cmCTestBuildAndTestHandler.h b/Source/CTest/cmCTestBuildAndTestHandler.h
index d1e9a4d..5a7b916 100644
--- a/Source/CTest/cmCTestBuildAndTestHandler.h
+++ b/Source/CTest/cmCTestBuildAndTestHandler.h
@@ -57,6 +57,7 @@
   std::string  Output;
 
   std::string              BuildGenerator;
+  std::string              BuildGeneratorPlatform;
   std::string              BuildGeneratorToolset;
   std::vector<std::string> BuildOptions;
   bool                     BuildTwoConfig;
diff --git a/Source/CTest/cmCTestBuildHandler.cxx b/Source/CTest/cmCTestBuildHandler.cxx
index 7922c9a..2ec1365 100644
--- a/Source/CTest/cmCTestBuildHandler.cxx
+++ b/Source/CTest/cmCTestBuildHandler.cxx
@@ -605,6 +605,9 @@
   typedef std::set<std::string, FragmentCompare> Fragments;
   Fragments fragments(fragmentCompare);
 
+  // only report the first 50 warnings and first 50 errors
+  int numErrorsAllowed = this->MaxErrors;
+  int numWarningsAllowed = this->MaxWarnings;
   // Identify fragments on disk.
   cmsys::Directory launchDir;
   launchDir.Load(this->CTestLaunchDir.c_str());
@@ -612,13 +615,15 @@
   for(unsigned long i=0; i < n; ++i)
     {
     const char* fname = launchDir.GetFile(i);
-    if(this->IsLaunchedErrorFile(fname))
+    if(this->IsLaunchedErrorFile(fname) && numErrorsAllowed)
       {
+      numErrorsAllowed--;
       fragments.insert(this->CTestLaunchDir + "/" + fname);
       ++this->TotalErrors;
       }
-    else if(this->IsLaunchedWarningFile(fname))
+    else if(this->IsLaunchedWarningFile(fname) && numWarningsAllowed)
       {
+      numWarningsAllowed--;
       fragments.insert(this->CTestLaunchDir + "/" + fname);
       ++this->TotalWarnings;
       }
diff --git a/Source/CTest/cmCTestConfigureCommand.cxx b/Source/CTest/cmCTestConfigureCommand.cxx
index 1aa8768..ef62fd3 100644
--- a/Source/CTest/cmCTestConfigureCommand.cxx
+++ b/Source/CTest/cmCTestConfigureCommand.cxx
@@ -118,6 +118,15 @@
       cmakeConfigureCommand += cmakeGeneratorName;
       cmakeConfigureCommand += "\"";
 
+      const char* cmakeGeneratorPlatform =
+        this->Makefile->GetDefinition("CTEST_CMAKE_GENERATOR_PLATFORM");
+      if(cmakeGeneratorPlatform && *cmakeGeneratorPlatform)
+        {
+        cmakeConfigureCommand += " \"-A";
+        cmakeConfigureCommand += cmakeGeneratorPlatform;
+        cmakeConfigureCommand += "\"";
+        }
+
       const char* cmakeGeneratorToolset =
         this->Makefile->GetDefinition("CTEST_CMAKE_GENERATOR_TOOLSET");
       if(cmakeGeneratorToolset && *cmakeGeneratorToolset)
diff --git a/Source/CTest/cmCTestConfigureHandler.cxx b/Source/CTest/cmCTestConfigureHandler.cxx
index a6e39a4..c492bf0 100644
--- a/Source/CTest/cmCTestConfigureHandler.cxx
+++ b/Source/CTest/cmCTestConfigureHandler.cxx
@@ -77,7 +77,7 @@
     this->StartLogFile("Configure", ofs);
     cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, "Configure with command: "
       << cCommand << std::endl);
-    res = this->CTest->RunMakeCommand(cCommand.c_str(), &output,
+    res = this->CTest->RunMakeCommand(cCommand.c_str(), output,
       &retVal, buildDirectory.c_str(),
       0, ofs);
 
diff --git a/Source/CTest/cmCTestCoverageHandler.cxx b/Source/CTest/cmCTestCoverageHandler.cxx
index da27c8c..76f6584 100644
--- a/Source/CTest/cmCTestCoverageHandler.cxx
+++ b/Source/CTest/cmCTestCoverageHandler.cxx
@@ -14,6 +14,7 @@
 #include "cmParseCoberturaCoverage.h"
 #include "cmParseGTMCoverage.h"
 #include "cmParseCacheCoverage.h"
+#include "cmParseJacocoCoverage.h"
 #include "cmCTest.h"
 #include "cmake.h"
 #include "cmMakefile.h"
@@ -415,6 +416,13 @@
     return error;
     }
 
+  file_count += this->HandleJacocoCoverage(&cont);
+  error = cont.Error;
+  if ( file_count < 0 )
+    {
+    return error;
+    }
+
   std::set<std::string> uncovered = this->FindUncoveredFiles(&cont);
 
   if ( file_count == 0 )
@@ -872,6 +880,38 @@
 };
 
 //----------------------------------------------------------------------
+int cmCTestCoverageHandler::HandleJacocoCoverage(
+  cmCTestCoverageHandlerContainer* cont)
+{
+  cmParseJacocoCoverage cov =
+   cmParseJacocoCoverage(*cont, this->CTest);
+  cmsys::Glob g;
+  std::vector<std::string> files;
+  g.SetRecurse(true);
+
+  std::string SourceDir
+    = this->CTest->GetCTestConfiguration("SourceDirectory");
+  std::string coverageFile = SourceDir+ "/*jacoco.xml";
+
+  g.FindFiles(coverageFile);
+  files=g.GetFiles();
+  if (files.size() > 0)
+    {
+    cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
+      "Found Jacoco Files, Performing Coverage" << std::endl);
+    cov.LoadCoverageData(files);
+    }
+  else
+    {
+    cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
+      " Cannot find Jacoco coverage files: " << coverageFile
+      << std::endl);
+    }
+  return static_cast<int>(cont->TotalCoverage.size());
+}
+
+
+//----------------------------------------------------------------------
 int cmCTestCoverageHandler::HandleGCovCoverage(
   cmCTestCoverageHandlerContainer* cont)
 {
diff --git a/Source/CTest/cmCTestCoverageHandler.h b/Source/CTest/cmCTestCoverageHandler.h
index 38a3353..d0f274c 100644
--- a/Source/CTest/cmCTestCoverageHandler.h
+++ b/Source/CTest/cmCTestCoverageHandler.h
@@ -81,7 +81,10 @@
   //! Handle coverage for mumps
   int HandleMumpsCoverage(cmCTestCoverageHandlerContainer* cont);
 
-  //! Handle coverage using Bullseye
+  //! Handle coverage for Jacoco
+  int HandleJacocoCoverage(cmCTestCoverageHandlerContainer* cont);
+
+//! Handle coverage using Bullseye
   int HandleBullseyeCoverage(cmCTestCoverageHandlerContainer* cont);
   int RunBullseyeSourceSummary(cmCTestCoverageHandlerContainer* cont);
   int RunBullseyeCoverageBranch(cmCTestCoverageHandlerContainer* cont,
diff --git a/Source/CTest/cmCTestMemCheckCommand.cxx b/Source/CTest/cmCTestMemCheckCommand.cxx
index 535c993..f144066 100644
--- a/Source/CTest/cmCTestMemCheckCommand.cxx
+++ b/Source/CTest/cmCTestMemCheckCommand.cxx
@@ -21,6 +21,10 @@
     = this->CTest->GetInitializedHandler("memcheck");
 
   this->CTest->SetCTestConfigurationFromCMakeVariable(this->Makefile,
+    "MemoryCheckType", "CTEST_MEMORYCHECK_TYPE");
+  this->CTest->SetCTestConfigurationFromCMakeVariable(this->Makefile,
+    "MemoryCheckSanitizerOptions", "CTEST_MEMORYCHECK_SANITIZER_OPTIONS");
+  this->CTest->SetCTestConfigurationFromCMakeVariable(this->Makefile,
     "MemoryCheckCommand", "CTEST_MEMORYCHECK_COMMAND");
   this->CTest->SetCTestConfigurationFromCMakeVariable(this->Makefile,
     "MemoryCheckCommandOptions", "CTEST_MEMORYCHECK_COMMAND_OPTIONS");
diff --git a/Source/CTest/cmCTestMemCheckHandler.cxx b/Source/CTest/cmCTestMemCheckHandler.cxx
index ecaa474..4835010 100644
--- a/Source/CTest/cmCTestMemCheckHandler.cxx
+++ b/Source/CTest/cmCTestMemCheckHandler.cxx
@@ -18,6 +18,7 @@
 #include <cmsys/Process.h>
 #include <cmsys/RegularExpression.hxx>
 #include <cmsys/Base64.h>
+#include <cmsys/Glob.hxx>
 #include <cmsys/FStream.hxx>
 #include "cmMakefile.h"
 #include "cmXMLSafe.h"
@@ -44,11 +45,23 @@
   {0,0}
 };
 
+static void xmlReportError(int line, const char* msg, void* data)
+{
+  cmCTest* ctest = (cmCTest*)data;
+  cmCTestLog(ctest, ERROR_MESSAGE,
+             "Error parsing XML in stream at line "
+             << line << ": " << msg << std::endl);
+}
+
 // parse the xml file containing the results of last BoundsChecker run
 class cmBoundsCheckerParser : public cmXMLParser
 {
 public:
-  cmBoundsCheckerParser(cmCTest* c) { this->CTest = c;}
+  cmBoundsCheckerParser(cmCTest* c)
+    {
+      this->CTest = c;
+      this->SetErrorCallback(xmlReportError, (void*)c);
+    }
   void StartElement(const std::string& name, const char** atts)
     {
       if(name == "MemoryLeak" ||
@@ -124,61 +137,8 @@
 
 #define BOUNDS_CHECKER_MARKER \
 "******######*****Begin BOUNDS CHECKER XML******######******"
-//----------------------------------------------------------------------
-static const char* cmCTestMemCheckResultStrings[] = {
-  "ABR",
-  "ABW",
-  "ABWL",
-  "COR",
-  "EXU",
-  "FFM",
-  "FIM",
-  "FMM",
-  "FMR",
-  "FMW",
-  "FUM",
-  "IPR",
-  "IPW",
-  "MAF",
-  "MLK",
-  "MPK",
-  "NPR",
-  "ODS",
-  "PAR",
-  "PLK",
-  "UMC",
-  "UMR",
-  0
-};
 
 
-//----------------------------------------------------------------------
-static const char* cmCTestMemCheckResultLongStrings[] = {
-  "Threading Problem",
-  "ABW",
-  "ABWL",
-  "COR",
-  "EXU",
-  "FFM",
-  "FIM",
-  "Mismatched deallocation",
-  "FMR",
-  "FMW",
-  "FUM",
-  "IPR",
-  "IPW",
-  "MAF",
-  "Memory Leak",
-  "Potential Memory Leak",
-  "NPR",
-  "ODS",
-  "Invalid syscall param",
-  "PLK",
-  "Uninitialized Memory Conditional",
-  "Uninitialized Memory Read",
-  0
-};
-
 
 //----------------------------------------------------------------------
 cmCTestMemCheckHandler::cmCTestMemCheckHandler()
@@ -186,12 +146,14 @@
   this->MemCheck = true;
   this->CustomMaximumPassedTestOutputSize = 0;
   this->CustomMaximumFailedTestOutputSize = 0;
+  this->LogWithPID = false;
 }
 
 //----------------------------------------------------------------------
 void cmCTestMemCheckHandler::Initialize()
 {
   this->Superclass::Initialize();
+  this->LogWithPID = false;
   this->CustomMaximumPassedTestOutputSize = 0;
   this->CustomMaximumFailedTestOutputSize = 0;
   this->MemoryTester = "";
@@ -199,12 +161,6 @@
   this->MemoryTesterOptions.clear();
   this->MemoryTesterStyle = UNKNOWN;
   this->MemoryTesterOutputFile = "";
-  int cc;
-  for ( cc = 0; cc < NO_MEMORY_FAULT; cc ++ )
-    {
-    this->MemoryTesterGlobalResults[cc] = 0;
-    }
-
 }
 
 //----------------------------------------------------------------------
@@ -249,8 +205,8 @@
   index = stream.str();
   for ( pp = 0; pp < this->MemoryTesterDynamicOptions.size(); pp ++ )
     {
-      std::string arg = this->MemoryTesterDynamicOptions[pp];
-      std::string::size_type pos = arg.find("??");
+    std::string arg = this->MemoryTesterDynamicOptions[pp];
+    std::string::size_type pos = arg.find("??");
     if (pos != std::string::npos)
       {
       arg.replace(pos, 2, index);
@@ -260,18 +216,125 @@
     memcheckcommand += arg;
     memcheckcommand += "\"";
     }
+  // Create a copy of the memory tester environment variable.
+  // This is used for memory testing programs that pass options
+  // via environment varaibles.
+  std::string memTesterEnvironmentVariable =
+    this->MemoryTesterEnvironmentVariable;
   for ( pp = 0; pp < this->MemoryTesterOptions.size(); pp ++ )
     {
-    args.push_back(this->MemoryTesterOptions[pp]);
-    memcheckcommand += " \"";
-    memcheckcommand += this->MemoryTesterOptions[pp];
-    memcheckcommand += "\"";
+    if(memTesterEnvironmentVariable.size())
+      {
+      // If we are using env to pass options, append all the options to
+      // this string with space separation.
+      memTesterEnvironmentVariable += " " + this->MemoryTesterOptions[pp];
+      }
+    // for regular options just add them to args and memcheckcommand
+    // which is just used for display
+    else
+      {
+      args.push_back(this->MemoryTesterOptions[pp]);
+      memcheckcommand += " \"";
+      memcheckcommand += this->MemoryTesterOptions[pp];
+      memcheckcommand += "\"";
+      }
+    }
+  // if this is an env option type, then add the env string as a single
+  // argument.
+  if(memTesterEnvironmentVariable.size())
+    {
+    std::string::size_type pos = memTesterEnvironmentVariable.find("??");
+    if (pos != std::string::npos)
+      {
+      memTesterEnvironmentVariable.replace(pos, 2, index);
+      }
+    memcheckcommand += " " + memTesterEnvironmentVariable;
+    args.push_back(memTesterEnvironmentVariable);
     }
   cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, "Memory check command: "
     << memcheckcommand << std::endl);
 }
 
 //----------------------------------------------------------------------
+void cmCTestMemCheckHandler::InitializeResultsVectors()
+{
+  // fill these members
+//  cmsys::vector<std::string> ResultStrings;
+//  cmsys::vector<std::string> ResultStringsLong;
+//  cmsys::vector<int>         GlobalResults;
+  this->ResultStringsLong.clear();
+  this->ResultStrings.clear();
+  this->GlobalResults.clear();
+  // If we are working with style checkers that dynamically fill
+  // the results strings then return.
+  if(this->MemoryTesterStyle > cmCTestMemCheckHandler::BOUNDS_CHECKER)
+    {
+    return;
+    }
+
+  // define the standard set of errors
+  //----------------------------------------------------------------------
+  static const char* cmCTestMemCheckResultStrings[] = {
+    "ABR",
+    "ABW",
+    "ABWL",
+    "COR",
+    "EXU",
+    "FFM",
+    "FIM",
+    "FMM",
+    "FMR",
+    "FMW",
+    "FUM",
+    "IPR",
+    "IPW",
+    "MAF",
+    "MLK",
+    "MPK",
+    "NPR",
+    "ODS",
+    "PAR",
+    "PLK",
+    "UMC",
+    "UMR",
+    0
+  };
+//----------------------------------------------------------------------
+  static const char* cmCTestMemCheckResultLongStrings[] = {
+    "Threading Problem",
+    "ABW",
+    "ABWL",
+    "COR",
+    "EXU",
+    "FFM",
+    "FIM",
+    "Mismatched deallocation",
+    "FMR",
+    "FMW",
+    "FUM",
+    "IPR",
+    "IPW",
+    "MAF",
+    "Memory Leak",
+    "Potential Memory Leak",
+    "NPR",
+    "ODS",
+    "Invalid syscall param",
+    "PLK",
+    "Uninitialized Memory Conditional",
+    "Uninitialized Memory Read",
+    0
+  };
+  this->GlobalResults.clear();
+  for(int i =0; cmCTestMemCheckResultStrings[i] != 0; ++i)
+    {
+    this->ResultStrings.push_back(cmCTestMemCheckResultStrings[i]);
+    this->ResultStringsLong.push_back(cmCTestMemCheckResultLongStrings[i]);
+    this->GlobalResults.push_back(0);
+    }
+}
+
+//----------------------------------------------------------------------
 void cmCTestMemCheckHandler::PopulateCustomVectors(cmMakefile *mf)
 {
   this->cmCTestTestHandler::PopulateCustomVectors(mf);
@@ -283,6 +346,8 @@
   this->CTest->PopulateCustomVector(mf,
                              "CTEST_CUSTOM_MEMCHECK_IGNORE",
                              this->CustomTestsIgnore);
+  std::string cmake = cmSystemTools::GetCMakeCommand();
+  this->CTest->SetCTestConfiguration("CMakeCommand", cmake.c_str());
 }
 
 //----------------------------------------------------------------------
@@ -292,7 +357,6 @@
     {
     return;
     }
-
   this->CTest->StartXML(os, this->AppendXML);
   os << "<DynamicAnalysis Checker=\"";
   switch ( this->MemoryTesterStyle )
@@ -306,6 +370,18 @@
     case cmCTestMemCheckHandler::BOUNDS_CHECKER:
       os << "BoundsChecker";
       break;
+    case cmCTestMemCheckHandler::ADDRESS_SANITIZER:
+      os << "AddressSanitizer";
+      break;
+    case cmCTestMemCheckHandler::THREAD_SANITIZER:
+      os << "ThreadSanitizer";
+      break;
+    case cmCTestMemCheckHandler::MEMORY_SANITIZER:
+      os << "MemorySanitizer";
+      break;
+    case cmCTestMemCheckHandler::UB_SANITIZER:
+      os << "UndefinedBehaviorSanitizer";
+      break;
     default:
       os << "Unknown";
     }
@@ -333,8 +409,7 @@
     {
     cmCTestTestResult *result = &this->TestResults[cc];
     std::string memcheckstr;
-    int memcheckresults[cmCTestMemCheckHandler::NO_MEMORY_FAULT];
-    int kk;
+    std::vector<int> memcheckresults(this->ResultStrings.size(), 0);
     bool res = this->ProcessMemCheckOutput(result->Output, memcheckstr,
       memcheckresults);
     if ( res && result->Status == cmCTestMemCheckHandler::COMPLETED )
@@ -345,16 +420,17 @@
       static_cast<size_t>(this->CustomMaximumFailedTestOutputSize));
     this->WriteTestResultHeader(os, result);
     os << "\t\t<Results>" << std::endl;
-    for ( kk = 0; cmCTestMemCheckResultLongStrings[kk]; kk ++ )
+    for(std::vector<int>::size_type kk = 0;
+        kk < memcheckresults.size(); ++kk)
       {
       if ( memcheckresults[kk] )
         {
-        os << "\t\t\t<Defect type=\"" << cmCTestMemCheckResultLongStrings[kk]
+        os << "\t\t\t<Defect type=\"" << this->ResultStringsLong[kk]
           << "\">"
            << memcheckresults[kk]
            << "</Defect>" << std::endl;
         }
-      this->MemoryTesterGlobalResults[kk] += memcheckresults[kk];
+      this->GlobalResults[kk] += memcheckresults[kk];
       }
 
     std::string logTag;
@@ -383,9 +459,9 @@
   cmCTestLog(this->CTest, HANDLER_OUTPUT, "Memory checking results:"
     << std::endl);
   os << "\t<DefectList>" << std::endl;
-  for ( cc = 0; cmCTestMemCheckResultStrings[cc]; cc ++ )
+  for ( cc = 0; cc < this->GlobalResults.size(); cc ++ )
     {
-    if ( this->MemoryTesterGlobalResults[cc] )
+    if ( this->GlobalResults[cc] )
       {
 #ifdef cerr
 #  undef cerr
@@ -393,9 +469,9 @@
       std::cerr.width(35);
 #define cerr no_cerr
       cmCTestLog(this->CTest, HANDLER_OUTPUT,
-        cmCTestMemCheckResultLongStrings[cc] << " - "
-        << this->MemoryTesterGlobalResults[cc] << std::endl);
-      os << "\t\t<Defect Type=\"" << cmCTestMemCheckResultLongStrings[cc]
+        this->ResultStringsLong[cc] << " - "
+        << this->GlobalResults[cc] << std::endl);
+      os << "\t\t<Defect Type=\"" << this->ResultStringsLong[cc]
         << "\"/>" << std::endl;
       }
     }
@@ -410,30 +486,33 @@
 
   os << "</DynamicAnalysis>" << std::endl;
   this->CTest->EndXML(os);
-
-
 }
 
 //----------------------------------------------------------------------
 bool cmCTestMemCheckHandler::InitializeMemoryChecking()
 {
+  this->MemoryTesterEnvironmentVariable = "";
+  this->MemoryTester = "";
   // Setup the command
   if ( cmSystemTools::FileExists(this->CTest->GetCTestConfiguration(
         "MemoryCheckCommand").c_str()) )
     {
     this->MemoryTester
       = this->CTest->GetCTestConfiguration("MemoryCheckCommand").c_str();
-
+    std::string testerName =
+      cmSystemTools::GetFilenameName(this->MemoryTester);
     // determine the checker type
-    if ( this->MemoryTester.find("valgrind") != std::string::npos )
+    if ( testerName.find("valgrind") != std::string::npos ||
+         this->CTest->GetCTestConfiguration("MemoryCheckType")
+         == "Valgrind")
       {
         this->MemoryTesterStyle = cmCTestMemCheckHandler::VALGRIND;
       }
-    else if ( this->MemoryTester.find("purify") != std::string::npos )
+    else if ( testerName.find("purify") != std::string::npos )
       {
       this->MemoryTesterStyle = cmCTestMemCheckHandler::PURIFY;
       }
-    else if ( this->MemoryTester.find("BC") != std::string::npos )
+    else if ( testerName.find("BC") != std::string::npos )
       {
       this->MemoryTesterStyle = cmCTestMemCheckHandler::BOUNDS_CHECKER;
       }
@@ -463,12 +542,62 @@
       = this->CTest->GetCTestConfiguration("BoundsCheckerCommand").c_str();
     this->MemoryTesterStyle = cmCTestMemCheckHandler::BOUNDS_CHECKER;
     }
-  else
+  if ( this->CTest->GetCTestConfiguration("MemoryCheckType")
+       == "AddressSanitizer")
+    {
+    this->MemoryTester
+      = this->CTest->GetCTestConfiguration("CMakeCommand").c_str();
+    this->MemoryTesterStyle = cmCTestMemCheckHandler::ADDRESS_SANITIZER;
+    this->LogWithPID = true; // even if we give the log file the pid is added
+    }
+  if ( this->CTest->GetCTestConfiguration("MemoryCheckType")
+       == "ThreadSanitizer")
+    {
+    this->MemoryTester
+      = this->CTest->GetCTestConfiguration("CMakeCommand").c_str();
+    this->MemoryTesterStyle = cmCTestMemCheckHandler::THREAD_SANITIZER;
+    this->LogWithPID = true; // even if we give the log file the pid is added
+    }
+  if ( this->CTest->GetCTestConfiguration("MemoryCheckType")
+       == "MemorySanitizer")
+    {
+    this->MemoryTester
+      = this->CTest->GetCTestConfiguration("CMakeCommand").c_str();
+    this->MemoryTesterStyle = cmCTestMemCheckHandler::MEMORY_SANITIZER;
+    this->LogWithPID = true; // even if we give the log file the pid is added
+    }
+  if ( this->CTest->GetCTestConfiguration("MemoryCheckType")
+       == "UndefinedBehaviorSanitizer")
+    {
+    this->MemoryTester
+      = this->CTest->GetCTestConfiguration("CMakeCommand").c_str();
+    this->MemoryTesterStyle = cmCTestMemCheckHandler::UB_SANITIZER;
+    this->LogWithPID = true; // even if we give the log file the pid is added
+    }
+  // Check the MemoryCheckType
+  if(this->MemoryTesterStyle == cmCTestMemCheckHandler::UNKNOWN)
+    {
+    std::string checkType =
+      this->CTest->GetCTestConfiguration("MemoryCheckType");
+    if(checkType == "Purify")
+      {
+      this->MemoryTesterStyle = cmCTestMemCheckHandler::PURIFY;
+      }
+    else if(checkType == "BoundsChecker")
+      {
+      this->MemoryTesterStyle = cmCTestMemCheckHandler::BOUNDS_CHECKER;
+      }
+    else if(checkType == "Valgrind")
+      {
+      this->MemoryTesterStyle = cmCTestMemCheckHandler::VALGRIND;
+      }
+    }
+  if(this->MemoryTester.size() == 0 )
     {
     cmCTestLog(this->CTest, WARNING,
-      "Memory checker (MemoryCheckCommand) "
-      "not set, or cannot find the specified program."
-      << std::endl);
+               "Memory checker (MemoryCheckCommand) "
+               "not set, or cannot find the specified program."
+               << std::endl);
     return false;
     }
 
@@ -567,6 +696,46 @@
       this->MemoryTesterOptions.push_back("/M");
       break;
       }
+      // these are almost the same but the env var used is different
+    case cmCTestMemCheckHandler::ADDRESS_SANITIZER:
+    case cmCTestMemCheckHandler::THREAD_SANITIZER:
+    case cmCTestMemCheckHandler::MEMORY_SANITIZER:
+    case cmCTestMemCheckHandler::UB_SANITIZER:
+      {
+      // To pass arguments to ThreadSanitizer the environment variable
+      // TSAN_OPTIONS is used. This is done with the cmake -E env command.
+      // The MemoryTesterDynamicOptions is setup with the -E env
+      // Then the MemoryTesterEnvironmentVariable gets the
+      // TSAN_OPTIONS string with the log_path in it.
+      this->MemoryTesterDynamicOptions.push_back("-E");
+      this->MemoryTesterDynamicOptions.push_back("env");
+      std::string envVar;
+      std::string extraOptions =
+        this->CTest->GetCTestConfiguration("MemoryCheckSanitizerOptions");
+      if(this->MemoryTesterStyle == cmCTestMemCheckHandler::ADDRESS_SANITIZER)
+        {
+        envVar = "ASAN_OPTIONS";
+        extraOptions += " detect_leaks=1";
+        }
+      else if(this->MemoryTesterStyle ==
+              cmCTestMemCheckHandler::THREAD_SANITIZER)
+        {
+        envVar = "TSAN_OPTIONS";
+        }
+      else if(this->MemoryTesterStyle ==
+              cmCTestMemCheckHandler::MEMORY_SANITIZER)
+        {
+        envVar = "MSAN_OPTIONS";
+        }
+      else if(this->MemoryTesterStyle == cmCTestMemCheckHandler::UB_SANITIZER)
+        {
+        envVar = "UBSAN_OPTIONS";
+        }
+      std::string outputFile = envVar + "=log_path=\""
+        + this->MemoryTesterOutputFile + "\" ";
+      this->MemoryTesterEnvironmentVariable = outputFile + extraOptions;
+      break;
+      }
     default:
       cmCTestLog(this->CTest, ERROR_MESSAGE,
         "Do not understand memory checker: " << this->MemoryTester
@@ -574,24 +743,20 @@
       return false;
     }
 
-  std::vector<std::string>::size_type cc;
-  for ( cc = 0; cmCTestMemCheckResultStrings[cc]; cc ++ )
-    {
-    this->MemoryTesterGlobalResults[cc] = 0;
-    }
+  this->InitializeResultsVectors();
+  // std::vector<std::string>::size_type cc;
+  // for ( cc = 0; cmCTestMemCheckResultStrings[cc]; cc ++ )
+  //   {
+  //   this->MemoryTesterGlobalResults[cc] = 0;
+  //   }
   return true;
 }
 
 //----------------------------------------------------------------------
-bool cmCTestMemCheckHandler::ProcessMemCheckOutput(const std::string& str,
-                                               std::string& log, int* results)
+bool cmCTestMemCheckHandler::
+ProcessMemCheckOutput(const std::string& str,
+                      std::string& log, std::vector<int>& results)
 {
-  std::string::size_type cc;
-  for ( cc = 0; cc < cmCTestMemCheckHandler::NO_MEMORY_FAULT; cc ++ )
-    {
-    results[cc] = 0;
-    }
-
   if ( this->MemoryTesterStyle == cmCTestMemCheckHandler::VALGRIND )
     {
     return this->ProcessMemCheckValgrindOutput(str, log, results);
@@ -601,6 +766,17 @@
     return this->ProcessMemCheckPurifyOutput(str, log, results);
     }
   else if ( this->MemoryTesterStyle ==
+            cmCTestMemCheckHandler::ADDRESS_SANITIZER ||
+            this->MemoryTesterStyle ==
+            cmCTestMemCheckHandler::THREAD_SANITIZER ||
+            this->MemoryTesterStyle ==
+            cmCTestMemCheckHandler::MEMORY_SANITIZER ||
+            this->MemoryTesterStyle ==
+            cmCTestMemCheckHandler::UB_SANITIZER)
+    {
+    return this->ProcessMemCheckSanitizerOutput(str, log, results);
+    }
+  else if ( this->MemoryTesterStyle ==
     cmCTestMemCheckHandler::BOUNDS_CHECKER )
     {
     return this->ProcessMemCheckBoundsCheckerOutput(str, log, results);
@@ -611,15 +787,94 @@
     log.append("None that I know");
     log = str;
     }
-
-
   return true;
 }
 
+std::vector<int>::size_type cmCTestMemCheckHandler::FindOrAddWarning(
+  const std::string& warning)
+{
+  for(std::vector<std::string>::size_type i =0;
+      i < this->ResultStrings.size(); ++i)
+    {
+    if(this->ResultStrings[i] == warning)
+      {
+      return i;
+      }
+    }
+  this->GlobalResults.push_back(0); // this must stay the same size
+  this->ResultStrings.push_back(warning);
+  this->ResultStringsLong.push_back(warning);
+  return this->ResultStrings.size()-1;
+}
+//----------------------------------------------------------------------
+bool cmCTestMemCheckHandler::ProcessMemCheckSanitizerOutput(
+  const std::string& str, std::string& log,
+  std::vector<int>& result)
+{
+  std::string regex;
+  switch ( this->MemoryTesterStyle )
+    {
+    case cmCTestMemCheckHandler::ADDRESS_SANITIZER:
+      regex = "ERROR: AddressSanitizer: (.*) on.*";
+      break;
+    case cmCTestMemCheckHandler::THREAD_SANITIZER:
+      regex = "WARNING: ThreadSanitizer: (.*) \\(pid=.*\\)";
+      break;
+    case cmCTestMemCheckHandler::MEMORY_SANITIZER:
+      regex = "WARNING: MemorySanitizer: (.*)";
+      break;
+    case cmCTestMemCheckHandler::UB_SANITIZER:
+      regex = "runtime error: (.*)";
+      break;
+    default:
+      break;
+    }
+  cmsys::RegularExpression sanitizerWarning(regex);
+  cmsys::RegularExpression leakWarning("(Direct|Indirect) leak of .*");
+  int defects = 0;
+  std::vector<std::string> lines;
+  cmSystemTools::Split(str.c_str(), lines);
+  cmOStringStream ostr;
+  log = "";
+  for( std::vector<std::string>::iterator i = lines.begin();
+       i != lines.end(); ++i)
+    {
+    std::string resultFound;
+    if(leakWarning.find(*i))
+      {
+      resultFound = leakWarning.match(1)+" leak";
+      }
+    else if (sanitizerWarning.find(*i))
+      {
+      resultFound = sanitizerWarning.match(1);
+      }
+    if(resultFound.size())
+      {
+      std::vector<int>::size_type idx = this->FindOrAddWarning(resultFound);
+      if(result.size() == 0 || idx > result.size()-1)
+        {
+        result.push_back(1);
+        }
+      else
+        {
+        result[idx]++;
+        }
+      defects++;
+      ostr << "<b>" <<  this->ResultStrings[idx] << "</b> ";
+      }
+    ostr << cmXMLSafe(*i) << std::endl;
+    }
+  log = ostr.str();
+  if(defects)
+    {
+    return false;
+    }
+  return true;
+}
 //----------------------------------------------------------------------
 bool cmCTestMemCheckHandler::ProcessMemCheckPurifyOutput(
   const std::string& str, std::string& log,
-  int* results)
+  std::vector<int>& results)
 {
   std::vector<std::string> lines;
   cmSystemTools::Split(str.c_str(), lines);
@@ -633,19 +888,19 @@
   for( std::vector<std::string>::iterator i = lines.begin();
        i != lines.end(); ++i)
     {
-    int failure = cmCTestMemCheckHandler::NO_MEMORY_FAULT;
+    std::vector<int>::size_type failure = this->ResultStrings.size();
     if ( pfW.find(*i) )
       {
-      int cc;
-      for ( cc = 0; cc < cmCTestMemCheckHandler::NO_MEMORY_FAULT; cc ++ )
+      std::vector<int>::size_type cc;
+      for ( cc = 0; cc < this->ResultStrings.size(); cc ++ )
         {
-        if ( pfW.match(1) == cmCTestMemCheckResultStrings[cc] )
+        if ( pfW.match(1) == this->ResultStrings[cc] )
           {
           failure = cc;
           break;
           }
         }
-      if ( cc == cmCTestMemCheckHandler::NO_MEMORY_FAULT )
+      if ( cc == this->ResultStrings.size() )
         {
         cmCTestLog(this->CTest, ERROR_MESSAGE, "Unknown Purify memory fault: "
           << pfW.match(1) << std::endl);
@@ -653,9 +908,9 @@
           << std::endl;
         }
       }
-    if ( failure != NO_MEMORY_FAULT )
+    if ( failure != this->ResultStrings.size() )
       {
-      ostr << "<b>" << cmCTestMemCheckResultStrings[failure] << "</b> ";
+      ostr << "<b>" <<  this->ResultStrings[failure] << "</b> ";
       results[failure] ++;
       defects ++;
       }
@@ -673,7 +928,7 @@
 //----------------------------------------------------------------------
 bool cmCTestMemCheckHandler::ProcessMemCheckValgrindOutput(
   const std::string& str, std::string& log,
-  int* results)
+  std::vector<int>& results)
 {
   std::vector<std::string> lines;
   cmSystemTools::Split(str.c_str(), lines);
@@ -728,7 +983,6 @@
   double sttime = cmSystemTools::GetTime();
   cmCTestLog(this->CTest, DEBUG, "Start test: " << lines.size() << std::endl);
   std::string::size_type totalOutputSize = 0;
-  bool outputFull = false;
   for ( cc = 0; cc < lines.size(); cc ++ )
     {
     cmCTestLog(this->CTest, DEBUG, "test line "
@@ -802,7 +1056,7 @@
 
       if ( failure != cmCTestMemCheckHandler::NO_MEMORY_FAULT )
         {
-        ostr << "<b>" << cmCTestMemCheckResultStrings[failure] << "</b> ";
+        ostr << "<b>" << this->ResultStrings[failure] << "</b> ";
         results[failure] ++;
         defects ++;
         }
@@ -815,32 +1069,30 @@
       }
     }
   // Now put all all the non valgrind output into the test output
-  if(!outputFull)
+  // This should be last in case it gets truncated by the output
+  // limiting code
+  for(std::vector<std::string::size_type>::iterator i =
+        nonValGrindOutput.begin(); i != nonValGrindOutput.end(); ++i)
     {
-    for(std::vector<std::string::size_type>::iterator i =
-          nonValGrindOutput.begin(); i != nonValGrindOutput.end(); ++i)
+    totalOutputSize += lines[*i].size();
+    cmCTestLog(this->CTest, DEBUG, "before xml safe "
+               << lines[*i] << std::endl);
+    cmCTestLog(this->CTest, DEBUG, "after  xml safe "
+               <<  cmXMLSafe(lines[*i]) << std::endl);
+    ostr << cmXMLSafe(lines[*i]) << std::endl;
+    if(!unlimitedOutput && totalOutputSize >
+       static_cast<size_t>(this->CustomMaximumFailedTestOutputSize))
       {
-      totalOutputSize += lines[*i].size();
-      cmCTestLog(this->CTest, DEBUG, "before xml safe "
-                 << lines[*i] << std::endl);
-      cmCTestLog(this->CTest, DEBUG, "after  xml safe "
-                 <<  cmXMLSafe(lines[*i]) << std::endl);
-
-      ostr << cmXMLSafe(lines[*i]) << std::endl;
-      if(!unlimitedOutput && totalOutputSize >
-         static_cast<size_t>(this->CustomMaximumFailedTestOutputSize))
-        {
-        outputFull = true;
-        ostr << "....\n";
-        ostr << "Test Output for this test has been truncated see testing"
-          " machine logs for full output,\n";
-        ostr << "or put CTEST_FULL_OUTPUT in the output of "
-          "this test program.\n";
-        }
+      ostr << "....\n";
+      ostr << "Test Output for this test has been truncated see testing"
+        " machine logs for full output,\n";
+      ostr << "or put CTEST_FULL_OUTPUT in the output of "
+        "this test program.\n";
+      break;  // stop the copy of output if we are full
       }
     }
   cmCTestLog(this->CTest, DEBUG, "End test (elapsed: "
-    << (cmSystemTools::GetTime() - sttime) << std::endl);
+             << (cmSystemTools::GetTime() - sttime) << std::endl);
   log = ostr.str();
   if ( defects )
     {
@@ -854,7 +1106,7 @@
 //----------------------------------------------------------------------
 bool cmCTestMemCheckHandler::ProcessMemCheckBoundsCheckerOutput(
   const std::string& str, std::string& log,
-  int* results)
+  std::vector<int>& results)
 {
   log = "";
   double sttime = cmSystemTools::GetTime();
@@ -908,6 +1160,32 @@
   return true;
 }
 
+// PostProcessTest memcheck results
+void
+cmCTestMemCheckHandler::PostProcessTest(cmCTestTestResult& res,
+                                        int test)
+{
+  cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
+             "PostProcessTest memcheck results for : "
+             << res.Name << std::endl);
+  if(this->MemoryTesterStyle
+     == cmCTestMemCheckHandler::BOUNDS_CHECKER)
+    {
+    this->PostProcessBoundsCheckerTest(res, test);
+    }
+  else
+    {
+    std::vector<std::string> files;
+    this->TestOutputFileNames(test, files);
+    for(std::vector<std::string>::iterator i = files.begin();
+        i != files.end(); ++i)
+      {
+      this->AppendMemTesterOutput(res, *i);
+      }
+    }
+}
+
+
 // This method puts the bounds checker output file into the output
 // for the test
 void
@@ -917,11 +1195,13 @@
   cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
              "PostProcessBoundsCheckerTest for : "
              << res.Name << std::endl);
-  std::string ofile = testOutputFileName(test);
-  if ( ofile.empty() )
+  std::vector<std::string> files;
+  this->TestOutputFileNames(test, files);
+  if ( files.size() == 0 )
     {
     return;
     }
+  std::string ofile = files[0];
   // put a scope around this to close ifs so the file can be removed
   {
   cmsys::ifstream ifs(ofile.c_str());
@@ -950,35 +1230,15 @@
 }
 
 void
-cmCTestMemCheckHandler::PostProcessPurifyTest(cmCTestTestResult& res,
-                                              int test)
+cmCTestMemCheckHandler::AppendMemTesterOutput(cmCTestTestResult& res,
+                                              std::string const& ofile)
 {
-  cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
-             "PostProcessPurifyTest for : "
-             << res.Name << std::endl);
-  appendMemTesterOutput(res, test);
-}
-
-void
-cmCTestMemCheckHandler::PostProcessValgrindTest(cmCTestTestResult& res,
-                                                int test)
-{
-  cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
-             "PostProcessValgrindTest for : "
-             << res.Name << std::endl);
-  appendMemTesterOutput(res, test);
-}
-
-void
-cmCTestMemCheckHandler::appendMemTesterOutput(cmCTestTestResult& res,
-                                              int test)
-{
-  std::string ofile = testOutputFileName(test);
-
   if ( ofile.empty() )
     {
     return;
     }
+  // put ifs in scope so file can be deleted if needed
+  {
   cmsys::ifstream ifs(ofile.c_str());
   if ( !ifs )
     {
@@ -992,10 +1252,17 @@
     res.Output += line;
     res.Output += "\n";
     }
+  }
+  if(this->LogWithPID)
+    {
+    cmSystemTools::RemoveFile(ofile.c_str());
+    cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, "Remove: "<< ofile <<"\n");
+    }
 }
 
-std::string
-cmCTestMemCheckHandler::testOutputFileName(int test)
+void cmCTestMemCheckHandler::TestOutputFileNames(int test,
+                                                 std::vector<std::string>&
+                                                 files)
 {
   std::string index;
   cmOStringStream stream;
@@ -1004,14 +1271,30 @@
   std::string ofile = this->MemoryTesterOutputFile;
   std::string::size_type pos = ofile.find("??");
   ofile.replace(pos, 2, index);
-
-  if ( !cmSystemTools::FileExists(ofile.c_str()) )
+  if(this->LogWithPID)
+    {
+    ofile += ".*";
+    cmsys::Glob g;
+    g.FindFiles(ofile);
+    if(g.GetFiles().size() == 0)
+      {
+      std::string log = "Cannot find memory tester output file: "
+        + ofile;
+      cmCTestLog(this->CTest, ERROR_MESSAGE, log.c_str() << std::endl);
+      ofile = "";
+      }
+    else
+      {
+      files = g.GetFiles();
+      return;
+      }
+    }
+  else if ( !cmSystemTools::FileExists(ofile.c_str()) )
     {
     std::string log = "Cannot find memory tester output file: "
       + ofile;
     cmCTestLog(this->CTest, ERROR_MESSAGE, log.c_str() << std::endl);
     ofile = "";
     }
-
-  return ofile;
+  files.push_back(ofile);
 }
diff --git a/Source/CTest/cmCTestMemCheckHandler.h b/Source/CTest/cmCTestMemCheckHandler.h
index 0521a48..69fdd9f 100644
--- a/Source/CTest/cmCTestMemCheckHandler.h
+++ b/Source/CTest/cmCTestMemCheckHandler.h
@@ -15,7 +15,10 @@
 
 
 #include "cmCTestTestHandler.h"
+#include "cmStandardIncludes.h"
 #include "cmListFileCache.h"
+#include <vector>
+#include <string>
 
 class cmMakefile;
 
@@ -45,7 +48,12 @@
     UNKNOWN = 0,
     VALGRIND,
     PURIFY,
-    BOUNDS_CHECKER
+    BOUNDS_CHECKER,
+    // checkers after here do not use the standard error list
+    ADDRESS_SANITIZER,
+    THREAD_SANITIZER,
+    MEMORY_SANITIZER,
+    UB_SANITIZER
   };
 public:
   enum { // Memory faults
@@ -93,7 +101,17 @@
   std::vector<std::string> MemoryTesterOptions;
   int                      MemoryTesterStyle;
   std::string              MemoryTesterOutputFile;
-  int                      MemoryTesterGlobalResults[NO_MEMORY_FAULT];
+  std::string              MemoryTesterEnvironmentVariable;
+  // these are used to store the types of errors that can show up
+  std::vector<std::string> ResultStrings;
+  std::vector<std::string> ResultStringsLong;
+  std::vector<int>         GlobalResults;
+  bool                     LogWithPID; // does log file add pid
+
+  std::vector<int>::size_type FindOrAddWarning(const std::string& warning);
+  // initialize the ResultStrings and ResultStringsLong for
+  // this type of checker
+  void InitializeResultsVectors();
 
   ///! Initialize memory checking subsystem.
   bool InitializeMemoryChecking();
@@ -110,24 +128,29 @@
   //string. After running, log holds the output and results hold the
   //different memmory errors.
   bool ProcessMemCheckOutput(const std::string& str,
-                             std::string& log, int* results);
+                             std::string& log, std::vector<int>& results);
   bool ProcessMemCheckValgrindOutput(const std::string& str,
-                                     std::string& log, int* results);
+                                     std::string& log,
+                                     std::vector<int>& results);
   bool ProcessMemCheckPurifyOutput(const std::string& str,
-                                   std::string& log, int* results);
+                                   std::string& log,
+                                   std::vector<int>& results);
+  bool ProcessMemCheckSanitizerOutput(const std::string& str,
+                                      std::string& log,
+                                      std::vector<int>& results);
   bool ProcessMemCheckBoundsCheckerOutput(const std::string& str,
-                                          std::string& log, int* results);
+                                          std::string& log,
+                                          std::vector<int>& results);
 
-  void PostProcessPurifyTest(cmCTestTestResult& res, int test);
+  void PostProcessTest(cmCTestTestResult& res, int test);
   void PostProcessBoundsCheckerTest(cmCTestTestResult& res, int test);
-  void PostProcessValgrindTest(cmCTestTestResult& res, int test);
 
   ///! append MemoryTesterOutputFile to the test log
-  void appendMemTesterOutput(cmCTestTestHandler::cmCTestTestResult& res,
-                             int test);
+  void AppendMemTesterOutput(cmCTestTestHandler::cmCTestTestResult& res,
+                             std::string const& filename);
 
   ///! generate the output filename for the given test index
-  std::string testOutputFileName(int test);
+  void TestOutputFileNames(int test, std::vector<std::string>& files);
 };
 
 #endif
diff --git a/Source/CTest/cmCTestMultiProcessHandler.cxx b/Source/CTest/cmCTestMultiProcessHandler.cxx
index b9e6721..7ba434c 100644
--- a/Source/CTest/cmCTestMultiProcessHandler.cxx
+++ b/Source/CTest/cmCTestMultiProcessHandler.cxx
@@ -319,8 +319,8 @@
 {
   std::string fname = this->CTest->GetCostDataFile();
   std::string tmpout = fname + ".tmp";
-  std::fstream fout;
-  fout.open(tmpout.c_str(), std::ios::out);
+  cmsys::ofstream fout;
+  fout.open(tmpout.c_str());
 
   PropertiesMap temp = this->Properties;
 
@@ -610,8 +610,8 @@
 {
   std::string fname = this->CTest->GetBinaryDir()
     + "/Testing/Temporary/CTestCheckpoint.txt";
-  std::fstream fout;
-  fout.open(fname.c_str(), std::ios::app | std::ios::out);
+  cmsys::ofstream fout;
+  fout.open(fname.c_str(), std::ios::app);
   fout << index << "\n";
   fout.close();
 }
diff --git a/Source/CTest/cmCTestRunTest.cxx b/Source/CTest/cmCTestRunTest.cxx
index 385388d..bdd8c02 100644
--- a/Source/CTest/cmCTestRunTest.cxx
+++ b/Source/CTest/cmCTestRunTest.cxx
@@ -392,20 +392,7 @@
              << this->TestResult.Name << std::endl);
   cmCTestMemCheckHandler * handler = static_cast<cmCTestMemCheckHandler*>
     (this->TestHandler);
-  switch ( handler->MemoryTesterStyle )
-    {
-    case cmCTestMemCheckHandler::VALGRIND:
-      handler->PostProcessValgrindTest(this->TestResult, this->Index);
-      break;
-    case cmCTestMemCheckHandler::PURIFY:
-      handler->PostProcessPurifyTest(this->TestResult, this->Index);
-      break;
-    case cmCTestMemCheckHandler::BOUNDS_CHECKER:
-      handler->PostProcessBoundsCheckerTest(this->TestResult, this->Index);
-      break;
-    default:
-      break;
-    }
+  handler->PostProcessTest(this->TestResult, this->Index);
 }
 
 //----------------------------------------------------------------------
diff --git a/Source/CTest/cmCTestScriptHandler.cxx b/Source/CTest/cmCTestScriptHandler.cxx
index 567acfc..f050148 100644
--- a/Source/CTest/cmCTestScriptHandler.cxx
+++ b/Source/CTest/cmCTestScriptHandler.cxx
@@ -317,6 +317,15 @@
   return retVal;
 }
 
+static void ctestScriptProgressCallback(const char *m, float, void* cd)
+{
+  cmCTest* ctest = static_cast<cmCTest*>(cd);
+  if(m && *m)
+    {
+    cmCTestLog(ctest, HANDLER_OUTPUT, "-- " << m << std::endl);
+    }
+}
+
 void cmCTestScriptHandler::CreateCMake()
 {
   // create a cmake instance to read the configuration script
@@ -334,6 +343,8 @@
   this->LocalGenerator = this->GlobalGenerator->CreateLocalGenerator();
   this->Makefile = this->LocalGenerator->GetMakefile();
 
+  this->CMake->SetProgressCallback(ctestScriptProgressCallback, this->CTest);
+
   // Set CMAKE_CURRENT_SOURCE_DIR and CMAKE_CURRENT_BINARY_DIR.
   // Also, some commands need Makefile->GetCurrentDirectory().
   std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
diff --git a/Source/CTest/cmCTestSubmitHandler.cxx b/Source/CTest/cmCTestSubmitHandler.cxx
index 7c72cba..06fcb75 100644
--- a/Source/CTest/cmCTestSubmitHandler.cxx
+++ b/Source/CTest/cmCTestSubmitHandler.cxx
@@ -225,8 +225,8 @@
       std::string upload_as
         = url + "/" + remoteprefix + cmSystemTools::GetFilenameName(*file);
 
-      struct stat st;
-      if ( ::stat(local_file.c_str(), &st) )
+
+      if ( !cmSystemTools::FileExists(local_file.c_str()) )
         {
         cmCTestLog(this->CTest, ERROR_MESSAGE, "   Cannot find file: "
           << local_file << std::endl);
@@ -234,6 +234,7 @@
         ::curl_global_cleanup();
         return false;
         }
+      unsigned long filelen = cmSystemTools::FileLength(local_file.c_str());
 
       ftpfile = cmsys::SystemTools::Fopen(local_file.c_str(), "rb");
       *this->LogFile << "\tUpload file: " << local_file << " to "
@@ -252,7 +253,7 @@
 
       // and give the size of the upload (optional)
       ::curl_easy_setopt(curl, CURLOPT_INFILESIZE,
-        static_cast<long>(st.st_size));
+        static_cast<long>(filelen));
 
       // and give curl the buffer for errors
       ::curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, &error_buffer);
@@ -466,8 +467,7 @@
         upload_as += md5;
         }
 
-      struct stat st;
-      if ( ::stat(local_file.c_str(), &st) )
+      if( !cmSystemTools::FileExists(local_file.c_str()) )
         {
         cmCTestLog(this->CTest, ERROR_MESSAGE, "   Cannot find file: "
           << local_file << std::endl);
@@ -475,11 +475,12 @@
         ::curl_global_cleanup();
         return false;
         }
+      unsigned long filelen = cmSystemTools::FileLength(local_file.c_str());
 
       ftpfile = cmsys::SystemTools::Fopen(local_file.c_str(), "rb");
       cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, "   Upload file: "
         << local_file << " to "
-        << upload_as << " Size: " << st.st_size << std::endl);
+        << upload_as << " Size: " << filelen << std::endl);
 
       // specify target
       ::curl_easy_setopt(curl,CURLOPT_URL, upload_as.c_str());
@@ -489,7 +490,7 @@
 
       // and give the size of the upload (optional)
       ::curl_easy_setopt(curl, CURLOPT_INFILESIZE,
-        static_cast<long>(st.st_size));
+        static_cast<long>(filelen));
 
       // and give curl the buffer for errors
       ::curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, &error_buffer);
@@ -1478,8 +1479,10 @@
 //----------------------------------------------------------------------------
 std::string cmCTestSubmitHandler::GetSubmitResultsPrefix()
 {
+  std::string buildname = cmCTest::SafeBuildIdField(
+    this->CTest->GetCTestConfiguration("BuildName"));
   std::string name = this->CTest->GetCTestConfiguration("Site") +
-    "___" + this->CTest->GetCTestConfiguration("BuildName") +
+    "___" + buildname +
     "___" + this->CTest->GetCurrentTag() + "-" +
     this->CTest->GetTestModelString() + "___XML___";
   return name;
diff --git a/Source/CTest/cmCTestUpdateCommand.cxx b/Source/CTest/cmCTestUpdateCommand.cxx
index 5408a8a..f87466d 100644
--- a/Source/CTest/cmCTestUpdateCommand.cxx
+++ b/Source/CTest/cmCTestUpdateCommand.cxx
@@ -56,6 +56,8 @@
   this->CTest->SetCTestConfigurationFromCMakeVariable(this->Makefile,
     "GITUpdateCustom", "CTEST_GIT_UPDATE_CUSTOM");
   this->CTest->SetCTestConfigurationFromCMakeVariable(this->Makefile,
+    "UpdateVersionOnly", "CTEST_UPDATE_VERSION_ONLY");
+  this->CTest->SetCTestConfigurationFromCMakeVariable(this->Makefile,
     "HGCommand", "CTEST_HG_COMMAND");
   this->CTest->SetCTestConfigurationFromCMakeVariable(this->Makefile,
     "HGUpdateOptions", "CTEST_HG_UPDATE_OPTIONS");
diff --git a/Source/CTest/cmCTestUpdateHandler.cxx b/Source/CTest/cmCTestUpdateHandler.cxx
index fda61ea..68f5fe1 100644
--- a/Source/CTest/cmCTestUpdateHandler.cxx
+++ b/Source/CTest/cmCTestUpdateHandler.cxx
@@ -258,12 +258,13 @@
   double elapsed_time_start = cmSystemTools::GetTime();
 
   bool updated = vc->Update();
-
+  std::string buildname = cmCTest::SafeBuildIdField(
+    this->CTest->GetCTestConfiguration("BuildName"));
   os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
     << "<Update mode=\"Client\" Generator=\"ctest-"
     << cmVersion::GetCMakeVersion() << "\">\n"
     << "\t<Site>" << this->CTest->GetCTestConfiguration("Site") << "</Site>\n"
-    << "\t<BuildName>" << this->CTest->GetCTestConfiguration("BuildName")
+    << "\t<BuildName>" << buildname
     << "</BuildName>\n"
     << "\t<BuildStamp>" << this->CTest->GetCurrentTag() << "-"
     << this->CTest->GetTestModelString() << "</BuildStamp>" << std::endl;
diff --git a/Source/CTest/cmCTestUploadHandler.cxx b/Source/CTest/cmCTestUploadHandler.cxx
index 4c3f81b..e33c387 100644
--- a/Source/CTest/cmCTestUploadHandler.cxx
+++ b/Source/CTest/cmCTestUploadHandler.cxx
@@ -44,14 +44,15 @@
       "Cannot open Upload.xml file" << std::endl);
     return -1;
     }
-
+  std::string buildname = cmCTest::SafeBuildIdField(
+    this->CTest->GetCTestConfiguration("BuildName"));
   cmCTest::SetOfStrings::const_iterator it;
   ofs << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
      << "<?xml-stylesheet type=\"text/xsl\" "
     "href=\"Dart/Source/Server/XSL/Build.xsl "
     "<file:///Dart/Source/Server/XSL/Build.xsl> \"?>\n"
      << "<Site BuildName=\""
-     << this->CTest->GetCTestConfiguration("BuildName")
+     << buildname
      << "\" BuildStamp=\""
      << this->CTest->GetCurrentTag() << "-"
      << this->CTest->GetTestModelString() << "\" Name=\""
diff --git a/Source/CTest/cmCTestVC.cxx b/Source/CTest/cmCTestVC.cxx
index f89fa2b..15f796f 100644
--- a/Source/CTest/cmCTestVC.cxx
+++ b/Source/CTest/cmCTestVC.cxx
@@ -166,10 +166,17 @@
 //----------------------------------------------------------------------------
 bool cmCTestVC::Update()
 {
-  this->NoteOldRevision();
-  this->Log << "--- Begin Update ---\n";
-  bool result = this->UpdateImpl();
-  this->Log << "--- End Update ---\n";
+  bool result = true;
+  // if update version only is on then do not actually update,
+  // just note the current version and finish
+  if(!cmSystemTools::IsOn(
+       this->CTest->GetCTestConfiguration("UpdateVersionOnly").c_str()))
+    {
+    this->NoteOldRevision();
+    this->Log << "--- Begin Update ---\n";
+    result = this->UpdateImpl();
+    this->Log << "--- End Update ---\n";
+    }
   this->NoteNewRevision();
   return result;
 }
diff --git a/Source/CTest/cmParseCoberturaCoverage.cxx b/Source/CTest/cmParseCoberturaCoverage.cxx
index 6b98056..0742be1 100644
--- a/Source/CTest/cmParseCoberturaCoverage.cxx
+++ b/Source/CTest/cmParseCoberturaCoverage.cxx
@@ -71,6 +71,7 @@
           cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, "Reading file: "
                      << atts[tagCount+1]<< std::endl);
           std::string filename = atts[tagCount+1];
+          this->CurFileName = "";
           for(size_t i=0;i < FilePaths.size();i++)
             {
             finalpath = FilePaths[i] + "/" + filename;
diff --git a/Source/CTest/cmParseJacocoCoverage.cxx b/Source/CTest/cmParseJacocoCoverage.cxx
new file mode 100644
index 0000000..f270adb
--- /dev/null
+++ b/Source/CTest/cmParseJacocoCoverage.cxx
@@ -0,0 +1,170 @@
+#include "cmStandardIncludes.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include "cmSystemTools.h"
+#include "cmXMLParser.h"
+#include "cmParseJacocoCoverage.h"
+#include <cmsys/Directory.hxx>
+#include <cmsys/Glob.hxx>
+#include <cmsys/FStream.hxx>
+
+
+class cmParseJacocoCoverage::XMLParser: public cmXMLParser
+{
+  public:
+    XMLParser(cmCTest* ctest, cmCTestCoverageHandlerContainer& cont)
+      : CTest(ctest), Coverage(cont)
+      {
+      this->PackageName = "";
+      this->ModuleName = "";
+      this->FileName = "";
+      this->CurFileName = "";
+      this->FilePaths.push_back(this->Coverage.SourceDir);
+      }
+
+    virtual ~XMLParser()
+      {
+      }
+
+  protected:
+
+    virtual void EndElement(const std::string&)
+      {
+      }
+
+    virtual void StartElement(const std::string& name,
+      const char** atts)
+      {
+      if(name == "package")
+        {
+        this->PackageName = atts[1];
+        std::string FilePath = this->Coverage.SourceDir +
+          "/" + this->ModuleName + "/src/main/java/" +
+          this->PackageName;
+        this->FilePaths.push_back(FilePath);
+        FilePath = this->Coverage.SourceDir +
+         "/src/main/java/" + this->PackageName;
+        this->FilePaths.push_back(FilePath);
+        }
+      else if(name == "sourcefile")
+        {
+        this->FileName = atts[1];
+        cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, "Reading file: "
+                     << this->FileName << std::endl);
+          for(size_t i=0;i < FilePaths.size();i++)
+            {
+            std::string finalpath = FilePaths[i] + "/" + this->FileName;
+            if(cmSystemTools::FileExists(finalpath.c_str()))
+              {
+              this->CurFileName = finalpath;
+              break;
+              }
+            }
+          cmsys::ifstream fin(this->CurFileName.c_str());
+          if(this->CurFileName == "" || !fin )
+          {
+            this->CurFileName = this->Coverage.BinaryDir + "/" +
+                                   this->FileName;
+            fin.open(this->CurFileName.c_str());
+            if (!fin)
+            {
+              cmCTestLog(this->CTest, ERROR_MESSAGE,
+                         "Jacoco Coverage: Error opening " << this->CurFileName
+                         << std::endl);
+              this->Coverage.Error++;
+            }
+          }
+          std::string line;
+          FileLinesType& curFileLines =
+            this->Coverage.TotalCoverage[this->CurFileName];
+          curFileLines.push_back(-1);
+          while(cmSystemTools::GetLineFromStream(fin, line))
+          {
+            curFileLines.push_back(-1);
+          }
+        }
+      else if(name == "report")
+        {
+        this->ModuleName=atts[1];
+        }
+      else if(name == "line")
+        {
+        int tagCount = 0;
+        int nr = -1;
+        int ci = -1;
+        while(true)
+          {
+          if(strcmp(atts[tagCount],"ci") == 0)
+            {
+            ci = atoi(atts[tagCount+1]);
+            }
+          else if (strcmp(atts[tagCount],"nr") == 0)
+            {
+            nr = atoi(atts[tagCount+1]);
+            }
+          if (ci > -1 && nr > 0)
+            {
+            FileLinesType& curFileLines=
+              this->Coverage.TotalCoverage[this->CurFileName];
+            if(curFileLines.size() > 0)
+               {
+               curFileLines[nr-1] = ci;
+               }
+            break;
+            }
+          ++tagCount;
+          }
+        }
+      }
+
+  private:
+    std::string PackageName;
+    std::string FileName;
+    std::string ModuleName;
+    std::string CurFileName;
+    std::vector<std::string> FilePaths;
+    typedef cmCTestCoverageHandlerContainer::SingleFileCoverageVector
+     FileLinesType;
+    cmCTest* CTest;
+    cmCTestCoverageHandlerContainer& Coverage;
+};
+
+cmParseJacocoCoverage::cmParseJacocoCoverage(
+  cmCTestCoverageHandlerContainer& cont,
+  cmCTest* ctest)
+  :Coverage(cont), CTest(ctest)
+  {
+  }
+
+bool cmParseJacocoCoverage::LoadCoverageData(
+  const std::vector<std::string> files)
+{
+  // load all the jacoco.xml files in the source directory
+  cmsys::Directory dir;
+  size_t i;
+  std::string path;
+  size_t numf = files.size();
+  for (i = 0; i < numf; i++)
+    {
+    path = files[i];
+
+    cmCTestLog(this->CTest,HANDLER_VERBOSE_OUTPUT,
+      "Reading XML File " << path  << std::endl);
+    if(cmSystemTools::GetFilenameLastExtension(path) == ".xml")
+      {
+      if(!this->ReadJacocoXML(path.c_str()))
+        {
+        return false;
+        }
+      }
+    }
+  return true;
+}
+
+bool cmParseJacocoCoverage::ReadJacocoXML(const char* file)
+{
+  cmParseJacocoCoverage::XMLParser
+    parser(this->CTest, this->Coverage);
+  parser.ParseFile(file);
+  return true;
+}
diff --git a/Source/CTest/cmParseJacocoCoverage.h b/Source/CTest/cmParseJacocoCoverage.h
new file mode 100644
index 0000000..dad05a3
--- /dev/null
+++ b/Source/CTest/cmParseJacocoCoverage.h
@@ -0,0 +1,59 @@
+/*============================================================================
+  CMake - Cross Platform Makefile Generator
+  Copyright 2000-2009 Kitware, Inc.
+
+  Distributed under the OSI-approved BSD License (the "License");
+  see accompanying file Copyright.txt for details.
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the License for more information.
+============================================================================*/
+
+#ifndef cmParseJacocoCoverage_h
+#define cmParseJacocoCoverage_h
+
+#include "cmStandardIncludes.h"
+#include "cmCTestCoverageHandler.h"
+
+
+/** \class cmParseJacocoCoverage
+ * \brief Parse JaCoCO coverage information
+ *
+ * This class is used to parse coverage information for
+ * java using the JaCoCo tool:
+ *
+ * http://www.eclemma.org/jacoco/trunk/index.html
+ */
+class cmParseJacocoCoverage
+{
+public:
+  cmParseJacocoCoverage(cmCTestCoverageHandlerContainer& cont,
+    cmCTest* ctest);
+  bool LoadCoverageData(const std::vector<std::string> files);
+
+  std::string PackageName;
+  std::string FileName;
+  std::string ModuleName;
+  std::string CurFileName;
+private:
+  // implement virtual from parent
+  // remove files with no coverage
+  void RemoveUnCoveredFiles();
+  // Read a single mcov file
+  bool ReadJacocoXML(const char* f);
+  // split a string based on ,
+  bool SplitString(std::vector<std::string>& args,
+    std::string const& line);
+  bool FindJavaFile(std::string const& routine,
+    std::string& filepath);
+  void InitializeJavaFile(std::string& file);
+  bool LoadSource(std::string d);
+
+  class XMLParser;
+  std::map<std::string, std::string> RoutineToDirectory;
+  cmCTestCoverageHandlerContainer& Coverage;
+  cmCTest* CTest;
+};
+
+#endif
diff --git a/Source/CTest/cmParseMumpsCoverage.cxx b/Source/CTest/cmParseMumpsCoverage.cxx
index 6236211..225e704 100644
--- a/Source/CTest/cmParseMumpsCoverage.cxx
+++ b/Source/CTest/cmParseMumpsCoverage.cxx
@@ -96,11 +96,13 @@
       }
     if(found)
       {
-      // (2) If the first character found above is whitespace then continue the
-      // search for the first following non-whitespace character.
+      // (2) If the first character found above is whitespace or a period
+      // then continue the search for the first following non-whitespace
+      // character.
       if(line[i] == ' ' || line[i] == '\t')
         {
-        while(i < line.size() && (line[i] == ' ' || line[i] == '\t'))
+        while(i < line.size() && (line[i] == ' ' || line[i] == '\t'
+          || line[i] == '.'))
           {
           i++;
           }
diff --git a/Source/CursesDialog/ccmake.cxx b/Source/CursesDialog/ccmake.cxx
index a9d4d98..28f3d9b 100644
--- a/Source/CursesDialog/ccmake.cxx
+++ b/Source/CursesDialog/ccmake.cxx
@@ -38,6 +38,18 @@
   {0,
    "  ccmake <path-to-source>\n"
    "  ccmake <path-to-existing-build>"},
+  {0,
+   "Specify a source directory to (re-)generate a build system for "
+   "it in the current working directory.  Specify an existing build "
+   "directory to re-generate its build system."},
+  {0,0}
+};
+
+//----------------------------------------------------------------------------
+static const char * cmDocumentationUsageNote[][2] =
+{
+  {0,
+   "Run 'ccmake --help' for more information."},
   {0,0}
 };
 
@@ -83,7 +95,7 @@
 
 int main(int argc, char const* const* argv)
 {
-  setlocale(LC_ALL, "");
+  setlocale(LC_CTYPE, "");
 
   cmsys::Encoding::CommandLineArguments encoding_args =
     cmsys::Encoding::CommandLineArguments::Main(argc, argv);
@@ -102,6 +114,10 @@
     doc.SetName("ccmake");
     doc.SetSection("Name",cmDocumentationName);
     doc.SetSection("Usage",cmDocumentationUsage);
+    if ( argc == 1 )
+      {
+      doc.AppendSection("Usage",cmDocumentationUsageNote);
+      }
     doc.SetSection("Generators",generators);
     doc.PrependSection("Options",cmDocumentationOptions);
     return doc.PrintRequestedDocumentation(std::cout)? 0:1;
diff --git a/Source/QtDialog/CMakeLists.txt b/Source/QtDialog/CMakeLists.txt
index 8da88c1..03c2fb4 100644
--- a/Source/QtDialog/CMakeLists.txt
+++ b/Source/QtDialog/CMakeLists.txt
@@ -35,6 +35,32 @@
 
   set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${Qt5Widgets_EXECUTABLE_COMPILE_FLAGS}")
 
+  # We need to install Cocoa platform plugin and add qt.conf for Qt5 on Mac.
+  # FIXME: This should be part of Qt5 CMake scripts, but unfortunatelly
+  # Qt5 Mac support is missing there.
+  if(APPLE)
+    macro(install_qt5_plugin _qt_plugin_name _qt_plugins_var)
+      get_target_property(_qt_plugin_path "${_qt_plugin_name}" LOCATION)
+      if(EXISTS "${_qt_plugin_path}")
+        get_filename_component(_qt_plugin_file "${_qt_plugin_path}" NAME)
+        get_filename_component(_qt_plugin_type "${_qt_plugin_path}" PATH)
+        get_filename_component(_qt_plugin_type "${_qt_plugin_type}" NAME)
+        set(_qt_plugin_dest "${CMAKE_INSTALL_PREFIX}/PlugIns/${_qt_plugin_type}")
+        install(FILES "${_qt_plugin_path}"
+          DESTINATION "${_qt_plugin_dest}")
+        set(${_qt_plugins_var}
+          "${${_qt_plugins_var}};${_qt_plugin_dest}/${_qt_plugin_file}")
+      else()
+        message(FATAL_ERROR "QT plugin ${_qt_plugin_name} not found")
+      endif()
+    endmacro()
+    install_qt5_plugin("Qt5::QCocoaIntegrationPlugin" QT_PLUGINS)
+    file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/qt.conf"
+      "[Paths]\nPlugins = PlugIns\n")
+    install(FILES "${CMAKE_CURRENT_BINARY_DIR}/qt.conf"
+      DESTINATION "${CMAKE_INSTALL_PREFIX}/Resources")
+  endif()
+
   if(WIN32 AND TARGET Qt5::Core)
     get_property(_Qt5_Core_LOCATION TARGET Qt5::Core PROPERTY LOCATION)
     get_filename_component(Qt_BIN_DIR "${_Qt5_Core_LOCATION}" PATH)
@@ -168,7 +194,7 @@
   install(CODE "
     include(\"${CMake_SOURCE_DIR}/Modules/BundleUtilities.cmake\")
     set(BU_CHMOD_BUNDLE_ITEMS ON)
-    fixup_bundle(\"${fixup_exe}\" \"\" \"${QT_LIBRARY_DIR};${QT_BINARY_DIR}\")
+    fixup_bundle(\"${fixup_exe}\" \"${QT_PLUGINS}\" \"${QT_LIBRARY_DIR};${QT_BINARY_DIR}\")
   ")
 endif()
 
diff --git a/Source/QtDialog/CMakeSetupDialog.cxx b/Source/QtDialog/CMakeSetupDialog.cxx
index 8a37797..0574681 100644
--- a/Source/QtDialog/CMakeSetupDialog.cxx
+++ b/Source/QtDialog/CMakeSetupDialog.cxx
@@ -756,6 +756,9 @@
       QString systemName = dialog.getSystemName();
       m->insertProperty(QCMakeProperty::STRING, "CMAKE_SYSTEM_NAME",
                         tr("CMake System Name"), systemName, false);
+      QString systemVersion = dialog.getSystemVersion();
+      m->insertProperty(QCMakeProperty::STRING, "CMAKE_SYSTEM_VERSION",
+                        tr("CMake System Version"), systemVersion, false);
       QString cxxCompiler = dialog.getCXXCompiler();
       m->insertProperty(QCMakeProperty::FILEPATH, "CMAKE_CXX_COMPILER",
                         tr("CXX compiler."), cxxCompiler, false);
diff --git a/Source/QtIFW/cmake.org.html b/Source/QtIFW/cmake.org.html
new file mode 100644
index 0000000..cf5649d
--- /dev/null
+++ b/Source/QtIFW/cmake.org.html
@@ -0,0 +1,7 @@
+<html>
+<head>
+<meta http-equiv="Refresh" content="0; url=http://cmake.org/" />
+</head>
+<body>
+</body>
+</html>
diff --git a/Source/QtIFW/installscript.qs.in b/Source/QtIFW/installscript.qs.in
new file mode 100644
index 0000000..5491611
--- /dev/null
+++ b/Source/QtIFW/installscript.qs.in
@@ -0,0 +1,24 @@
+function Component()
+{
+    // default constructor
+}
+
+Component.prototype.createOperations = function()
+{
+    // call default implementation to actually install applications!
+    component.createOperations();
+
+    // Create shortcut
+    if (installer.value("os") === "win") {
+
+@_CPACK_IFW_SHORTCUT_OPTIONAL@
+
+        component.addOperation("CreateShortcut",
+                               installer.value("TargetDir") + "/cmake.org.html",
+                               installer.value("StartMenuDir") + "/CMake Web Site.lnk");
+
+        component.addOperation("CreateShortcut",
+                               installer.value("TargetDir") + "/uninstall.exe",
+                               installer.value("StartMenuDir") + "/Uninstall.lnk");
+    }
+}
diff --git a/Source/cmArchiveWrite.cxx b/Source/cmArchiveWrite.cxx
index 58f7573..a2aecac 100644
--- a/Source/cmArchiveWrite.cxx
+++ b/Source/cmArchiveWrite.cxx
@@ -25,6 +25,28 @@
 }
 
 //----------------------------------------------------------------------------
+static void cm_archive_entry_copy_pathname(struct archive_entry* e,
+  const std::string& dest)
+{
+#if cmsys_STL_HAS_WSTRING
+  archive_entry_copy_pathname_w(e, cmsys::Encoding::ToWide(dest).c_str());
+#else
+  archive_entry_copy_pathname(e, dest.c_str());
+#endif
+}
+
+//----------------------------------------------------------------------------
+static void cm_archive_entry_copy_sourcepath(struct archive_entry* e,
+  const std::string& file)
+{
+#if cmsys_STL_HAS_WSTRING
+  archive_entry_copy_sourcepath_w(e, cmsys::Encoding::ToWide(file).c_str());
+#else
+  archive_entry_copy_sourcepath(e, file.c_str());
+#endif
+}
+
+//----------------------------------------------------------------------------
 class cmArchiveWrite::Entry
 {
   struct archive_entry* Object;
@@ -137,7 +159,15 @@
         this->Error += cm_archive_error_string(this->Archive);
         return;
         }
-    break;
+      break;
+    case Type7Zip:
+      if(archive_write_set_format_7zip(this->Archive) != ARCHIVE_OK)
+        {
+        this->Error = "archive_write_set_format_7zip: ";
+        this->Error += cm_archive_error_string(this->Archive);
+        return;
+        }
+      break;
     }
 
   // do not pad the last block!!
@@ -237,8 +267,8 @@
     std::cout << dest << "\n";
     }
   Entry e;
-  archive_entry_copy_sourcepath(e, file);
-  archive_entry_set_pathname(e, dest.c_str());
+  cm_archive_entry_copy_sourcepath(e, file);
+  cm_archive_entry_copy_pathname(e, dest);
   if(archive_read_disk_entry_from_file(this->Disk, e, -1, 0) != ARCHIVE_OK)
     {
     this->Error = "archive_read_disk_entry_from_file: ";
diff --git a/Source/cmArchiveWrite.h b/Source/cmArchiveWrite.h
index 3e3b2f0..a6dcc0e 100644
--- a/Source/cmArchiveWrite.h
+++ b/Source/cmArchiveWrite.h
@@ -42,7 +42,8 @@
   enum Type
   {
     TypeTAR,
-    TypeZIP
+    TypeZIP,
+    Type7Zip
   };
 
   /** Construct with output stream to which to write archive.  */
diff --git a/Source/cmBootstrapCommands2.cxx b/Source/cmBootstrapCommands2.cxx
index be72526..5675295 100644
--- a/Source/cmBootstrapCommands2.cxx
+++ b/Source/cmBootstrapCommands2.cxx
@@ -14,6 +14,8 @@
 // This is sort of a boot strapping approach since you would
 // like to have CMake to build CMake.
 #include "cmCommands.h"
+#include "cmConditionEvaluator.cxx"
+#include "cmExpandedCommandArgument.cxx"
 #include "cmGeneratorExpressionEvaluationFile.cxx"
 #include "cmGetCMakePropertyCommand.cxx"
 #include "cmGetDirectoryPropertyCommand.cxx"
diff --git a/Source/cmCTest.cxx b/Source/cmCTest.cxx
index d797d3b..a7905a4 100644
--- a/Source/cmCTest.cxx
+++ b/Source/cmCTest.cxx
@@ -488,9 +488,11 @@
     {
     cmCTestLog(this, DEBUG, "Here: " << __LINE__ << std::endl);
     cmCTestLog(this, OUTPUT,
-      "   Site: " << this->GetCTestConfiguration("Site") << std::endl
-      << "   Build name: " << this->GetCTestConfiguration("BuildName")
-      << std::endl);
+               "   Site: " << this->GetCTestConfiguration("Site") << std::endl
+               << "   Build name: "
+               << cmCTest::SafeBuildIdField(
+                 this->GetCTestConfiguration("BuildName"))
+               << std::endl);
     cmCTestLog(this, DEBUG, "Produce XML is on" << std::endl);
     if ( this->TestModel == cmCTest::NIGHTLY &&
          this->GetCTestConfiguration("NightlyStartTime").empty() )
@@ -1147,7 +1149,7 @@
 //######################################################################
 
 //----------------------------------------------------------------------
-int cmCTest::RunMakeCommand(const char* command, std::string* output,
+int cmCTest::RunMakeCommand(const char* command, std::string& output,
   int* retVal, const char* dir, int timeout, std::ostream& ofs)
 {
   // First generate the command and arguments
@@ -1166,11 +1168,7 @@
     }
   argv.push_back(0);
 
-  if ( output )
-    {
-    *output = "";
-    }
-
+  output = "";
   cmCTestLog(this, HANDLER_VERBOSE_OUTPUT, "Run command:");
   std::vector<const char*>::iterator ait;
   for ( ait = argv.begin(); ait != argv.end() && *ait; ++ ait )
@@ -1199,27 +1197,25 @@
     << "    " << std::flush);
   while(cmsysProcess_WaitForData(cp, &data, &length, 0))
     {
-    if ( output )
+    for(int cc =0; cc < length; ++cc)
       {
-      for(int cc =0; cc < length; ++cc)
+      if(data[cc] == 0)
         {
-        if(data[cc] == 0)
-          {
-          data[cc] = '\n';
-          }
+        data[cc] = '\n';
         }
-
-      output->append(data, length);
-      while ( output->size() > (tick * tick_len) )
+      }
+    output.append(data, length);
+    while ( output.size() > (tick * tick_len) )
+      {
+      tick ++;
+      cmCTestLog(this, HANDLER_OUTPUT, "." << std::flush);
+      if ( tick % tick_line_len == 0 && tick > 0 )
         {
-        tick ++;
-        cmCTestLog(this, HANDLER_OUTPUT, "." << std::flush);
-        if ( tick % tick_line_len == 0 && tick > 0 )
-          {
-          cmCTestLog(this, HANDLER_OUTPUT, "  Size: "
-            << int((double(output->size()) / 1024.0) + 1) << "K" << std::endl
-            << "    " << std::flush);
-          }
+        cmCTestLog(this, HANDLER_OUTPUT,
+                   "  Size: "
+                   << int((double(output.size()) / 1024.0) + 1)
+                   << "K" << std::endl
+                   << "    " << std::flush);
         }
       }
     cmCTestLog(this, HANDLER_VERBOSE_OUTPUT, cmCTestLogWrite(data, length));
@@ -1229,7 +1225,7 @@
       }
     }
   cmCTestLog(this, OUTPUT, " Size of output: "
-    << int(double(output->size()) / 1024.0) << "K" << std::endl);
+    << int(double(output.size()) / 1024.0) << "K" << std::endl);
 
   cmsysProcess_WaitForExit(cp, 0);
 
@@ -1253,9 +1249,9 @@
     }
   else if(result == cmsysProcess_State_Error)
     {
-    *output += "\n*** ERROR executing: ";
-    *output += cmsysProcess_GetErrorString(cp);
-    *output += "\n***The build process failed.";
+    output += "\n*** ERROR executing: ";
+    output += cmsysProcess_GetErrorString(cp);
+    output += "\n***The build process failed.";
     cmCTestLog(this, ERROR_MESSAGE, "There was an error: "
       << cmsysProcess_GetErrorString(cp) << std::endl);
     }
@@ -1447,7 +1443,7 @@
     // Disallow non-filename and non-space whitespace characters.
     // If they occur, replace them with ""
     //
-    const char *disallowed = "\\/:*?\"<>|\n\r\t\f\v";
+    const char *disallowed = "\\:*?\"<>|\n\r\t\f\v";
 
     if (safevalue.find_first_of(disallowed) != value.npos)
       {
@@ -1588,12 +1584,14 @@
 int cmCTest::GenerateCTestNotesOutput(std::ostream& os,
   const cmCTest::VectorOfStrings& files)
 {
+  std::string buildname = cmCTest::SafeBuildIdField(
+    this->GetCTestConfiguration("BuildName"));
   cmCTest::VectorOfStrings::const_iterator it;
   os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
      << "<?xml-stylesheet type=\"text/xsl\" "
     "href=\"Dart/Source/Server/XSL/Build.xsl "
     "<file:///Dart/Source/Server/XSL/Build.xsl> \"?>\n"
-     << "<Site BuildName=\"" << this->GetCTestConfiguration("BuildName")
+     << "<Site BuildName=\"" << buildname
      << "\" BuildStamp=\""
      << this->CurrentTag << "-" << this->GetTestModelString() << "\" Name=\""
      << this->GetCTestConfiguration("Site") << "\" Generator=\"ctest"
diff --git a/Source/cmCTest.h b/Source/cmCTest.h
index 246294f..e19d32c 100644
--- a/Source/cmCTest.h
+++ b/Source/cmCTest.h
@@ -271,7 +271,7 @@
 
   //! Run command specialized for make and configure. Returns process status
   // and retVal is return value or exception.
-  int RunMakeCommand(const char* command, std::string* output,
+  int RunMakeCommand(const char* command, std::string& output,
     int* retVal, const char* dir, int timeout,
     std::ostream& ofs);
 
diff --git a/Source/cmComputeLinkDepends.cxx b/Source/cmComputeLinkDepends.cxx
index 995f191..b13a125 100644
--- a/Source/cmComputeLinkDepends.cxx
+++ b/Source/cmComputeLinkDepends.cxx
@@ -166,18 +166,17 @@
 
 The final list of items produced by this procedure consists of the
 original user link line followed by minimal additional items needed to
-satisfy dependencies.
+satisfy dependencies.  The final list is then filtered to de-duplicate
+items that we know the linker will re-use automatically (shared libs).
 
 */
 
 //----------------------------------------------------------------------------
 cmComputeLinkDepends
-::cmComputeLinkDepends(cmTarget const* target, const std::string& config,
-                       cmTarget const* head)
+::cmComputeLinkDepends(cmTarget const* target, const std::string& config)
 {
   // Store context information.
   this->Target = target;
-  this->HeadTarget = head;
   this->Makefile = this->Target->GetMakefile();
   this->LocalGenerator = this->Makefile->GetLocalGenerator();
   this->GlobalGenerator = this->LocalGenerator->GetGlobalGenerator();
@@ -264,10 +263,20 @@
   this->OrderLinkEntires();
 
   // Compute the final set of link entries.
+  std::set<int> emmitted;
   for(std::vector<int>::const_iterator li = this->FinalLinkOrder.begin();
       li != this->FinalLinkOrder.end(); ++li)
     {
-    this->FinalLinkEntries.push_back(this->EntryList[*li]);
+    int i = *li;
+    LinkEntry const& e = this->EntryList[i];
+    cmTarget const* t = e.Target;
+    // Entries that we know the linker will re-use for symbols
+    // needed by later entries do not need to be repeated.
+    bool uniquify = t && t->GetType() == cmTarget::SHARED_LIBRARY;
+    if(!uniquify || emmitted.insert(i).second)
+      {
+      this->FinalLinkEntries.push_back(e);
+      }
     }
 
   // Display the final set.
@@ -294,8 +303,7 @@
 }
 
 //----------------------------------------------------------------------------
-int cmComputeLinkDepends::AddLinkEntry(int depender_index,
-                                       std::string const& item)
+int cmComputeLinkDepends::AddLinkEntry(cmLinkItem const& item)
 {
   // Check if the item entry has already been added.
   std::map<std::string, int>::iterator lei = this->LinkEntryIndex.find(item);
@@ -312,7 +320,7 @@
   int index = lei->second;
   LinkEntry& entry = this->EntryList[index];
   entry.Item = item;
-  entry.Target = this->FindTargetToLink(depender_index, entry.Item);
+  entry.Target = item.Target;
   entry.IsFlag = (!entry.Target && item[0] == '-' && item[1] != 'l' &&
                   item.substr(0, 10) != "-framework");
 
@@ -356,7 +364,7 @@
     {
     // Follow the target dependencies.
     if(cmTarget::LinkInterface const* iface =
-       entry.Target->GetLinkInterface(this->Config, this->HeadTarget))
+       entry.Target->GetLinkInterface(this->Config, this->Target))
       {
       const bool isIface =
                       entry.Target->GetType() == cmTarget::INTERFACE_LIBRARY;
@@ -372,11 +380,11 @@
       this->FollowSharedDeps(depender_index, iface);
 
       // Support for CMP0003.
-      for(std::vector<std::string>::const_iterator
+      for(std::vector<cmLinkItem>::const_iterator
             oi = iface->WrongConfigLibraries.begin();
           oi != iface->WrongConfigLibraries.end(); ++oi)
         {
-        this->CheckWrongConfigItem(depender_index, *oi);
+        this->CheckWrongConfigItem(*oi);
         }
       }
     }
@@ -408,9 +416,9 @@
 void
 cmComputeLinkDepends
 ::QueueSharedDependencies(int depender_index,
-                          std::vector<std::string> const& deps)
+                          std::vector<cmLinkItem> const& deps)
 {
-  for(std::vector<std::string>::const_iterator li = deps.begin();
+  for(std::vector<cmLinkItem>::const_iterator li = deps.begin();
       li != deps.end(); ++li)
     {
     SharedDepEntry qe;
@@ -434,8 +442,7 @@
     // Initialize the item entry.
     LinkEntry& entry = this->EntryList[lei->second];
     entry.Item = dep.Item;
-    entry.Target = this->FindTargetToLink(dep.DependerIndex,
-                                          dep.Item);
+    entry.Target = dep.Item.Target;
 
     // This item was added specifically because it is a dependent
     // shared library.  It may get special treatment
@@ -455,7 +462,7 @@
   if(entry.Target)
     {
     if(cmTarget::LinkInterface const* iface =
-       entry.Target->GetLinkInterface(this->Config, this->HeadTarget))
+       entry.Target->GetLinkInterface(this->Config, this->Target))
       {
       // Follow public and private dependencies transitively.
       this->FollowSharedDeps(index, iface, true);
@@ -474,7 +481,7 @@
   cmSystemTools::ExpandListArgument(value, deplist);
 
   // Look for entries meant for this configuration.
-  std::vector<std::string> actual_libs;
+  std::vector<cmLinkItem> actual_libs;
   cmTarget::LinkLibraryType llt = cmTarget::GENERAL;
   bool haveLLT = false;
   for(std::vector<std::string>::const_iterator di = deplist.begin();
@@ -522,11 +529,13 @@
       // If the library is meant for this link type then use it.
       if(llt == cmTarget::GENERAL || llt == this->LinkType)
         {
-        actual_libs.push_back(*di);
+        cmLinkItem item(*di, this->FindTargetToLink(depender_index, *di));
+        actual_libs.push_back(item);
         }
       else if(this->OldLinkDirMode)
         {
-        this->CheckWrongConfigItem(depender_index, *di);
+        cmLinkItem item(*di, this->FindTargetToLink(depender_index, *di));
+        this->CheckWrongConfigItem(item);
         }
 
       // Reset the link type until another explicit type is given.
@@ -544,38 +553,39 @@
 {
   // Add direct link dependencies in this configuration.
   cmTarget::LinkImplementation const* impl =
-    this->Target->GetLinkImplementation(this->Config, this->HeadTarget);
+    this->Target->GetLinkImplementation(this->Config);
   this->AddLinkEntries(-1, impl->Libraries);
-  for(std::vector<std::string>::const_iterator
+  for(std::vector<cmLinkItem>::const_iterator
         wi = impl->WrongConfigLibraries.begin();
       wi != impl->WrongConfigLibraries.end(); ++wi)
     {
-    this->CheckWrongConfigItem(-1, *wi);
+    this->CheckWrongConfigItem(*wi);
     }
 }
 
 //----------------------------------------------------------------------------
+template <typename T>
 void
-cmComputeLinkDepends::AddLinkEntries(int depender_index,
-                                     std::vector<std::string> const& libs)
+cmComputeLinkDepends::AddLinkEntries(
+  int depender_index, std::vector<T> const& libs)
 {
   // Track inferred dependency sets implied by this list.
   std::map<int, DependSet> dependSets;
 
   // Loop over the libraries linked directly by the depender.
-  for(std::vector<std::string>::const_iterator li = libs.begin();
+  for(typename std::vector<T>::const_iterator li = libs.begin();
       li != libs.end(); ++li)
     {
     // Skip entries that will resolve to the target getting linked or
     // are empty.
-    std::string item = this->Target->CheckCMP0004(*li);
+    cmLinkItem const& item = *li;
     if(item == this->Target->GetName() || item.empty())
       {
       continue;
       }
 
     // Add a link entry for this item.
-    int dependee_index = this->AddLinkEntry(depender_index, item);
+    int dependee_index = this->AddLinkEntry(*li);
 
     // The dependee must come after the depender.
     if(depender_index >= 0)
@@ -625,40 +635,15 @@
                                                  const std::string& name)
 {
   // Look for a target in the scope of the depender.
-  cmMakefile* mf = this->Makefile;
+  cmTarget const* from = this->Target;
   if(depender_index >= 0)
     {
     if(cmTarget const* depender = this->EntryList[depender_index].Target)
       {
-      mf = depender->GetMakefile();
+      from = depender;
       }
     }
-  cmTarget const* tgt = mf->FindTargetToUse(name);
-
-  // Skip targets that will not really be linked.  This is probably a
-  // name conflict between an external library and an executable
-  // within the project.
-  if(tgt && tgt->GetType() == cmTarget::EXECUTABLE &&
-     !tgt->IsExecutableWithExports())
-    {
-    tgt = 0;
-    }
-
-  if(tgt && tgt->GetType() == cmTarget::OBJECT_LIBRARY)
-    {
-    cmOStringStream e;
-    e << "Target \"" << this->Target->GetName() << "\" links to "
-      "OBJECT library \"" << tgt->GetName() << "\" but this is not "
-      "allowed.  "
-      "One may link only to STATIC or SHARED libraries, or to executables "
-      "with the ENABLE_EXPORTS property set.";
-    this->CMakeInstance->IssueMessage(cmake::FATAL_ERROR, e.str(),
-                                      this->Target->GetBacktrace());
-    tgt = 0;
-    }
-
-  // Return the target found, if any.
-  return tgt;
+  return from->FindTargetToLink(name);
 }
 
 //----------------------------------------------------------------------------
@@ -955,7 +940,7 @@
     if(cmTarget const* target = this->EntryList[*ni].Target)
       {
       if(cmTarget::LinkInterface const* iface =
-         target->GetLinkInterface(this->Config, this->HeadTarget))
+         target->GetLinkInterface(this->Config, this->Target))
         {
         if(iface->Multiplicity > count)
           {
@@ -988,8 +973,7 @@
 }
 
 //----------------------------------------------------------------------------
-void cmComputeLinkDepends::CheckWrongConfigItem(int depender_index,
-                                                std::string const& item)
+void cmComputeLinkDepends::CheckWrongConfigItem(cmLinkItem const& item)
 {
   if(!this->OldLinkDirMode)
     {
@@ -999,12 +983,8 @@
   // For CMake 2.4 bug-compatibility we need to consider the output
   // directories of targets linked in another configuration as link
   // directories.
-  if(cmTarget const* tgt
-                      = this->FindTargetToLink(depender_index, item))
+  if(item.Target && !item.Target->IsImported())
     {
-    if(!tgt->IsImported())
-      {
-      this->OldWrongConfigItems.insert(tgt);
-      }
+    this->OldWrongConfigItems.insert(item.Target);
     }
 }
diff --git a/Source/cmComputeLinkDepends.h b/Source/cmComputeLinkDepends.h
index 13fc993..a931726 100644
--- a/Source/cmComputeLinkDepends.h
+++ b/Source/cmComputeLinkDepends.h
@@ -32,8 +32,7 @@
 class cmComputeLinkDepends
 {
 public:
-  cmComputeLinkDepends(cmTarget const* target, const std::string& config,
-                       cmTarget const* head);
+  cmComputeLinkDepends(cmTarget const* target, const std::string& config);
   ~cmComputeLinkDepends();
 
   // Basic information about each link item.
@@ -60,7 +59,6 @@
 
   // Context information.
   cmTarget const* Target;
-  cmTarget const* HeadTarget;
   cmMakefile* Makefile;
   cmLocalGenerator* LocalGenerator;
   cmGlobalGenerator const* GlobalGenerator;
@@ -79,11 +77,11 @@
 
   std::map<std::string, int>::iterator
   AllocateLinkEntry(std::string const& item);
-  int AddLinkEntry(int depender_index, std::string const& item);
+  int AddLinkEntry(cmLinkItem const& item);
   void AddVarLinkEntries(int depender_index, const char* value);
   void AddDirectLinkEntries();
-  void AddLinkEntries(int depender_index,
-                      std::vector<std::string> const& libs);
+  template <typename T>
+    void AddLinkEntries(int depender_index, std::vector<T> const& libs);
   cmTarget const* FindTargetToLink(int depender_index,
                                    const std::string& name);
 
@@ -105,7 +103,7 @@
   // of the interface.
   struct SharedDepEntry
   {
-    std::string Item;
+    cmLinkItem Item;
     int DependerIndex;
   };
   std::queue<SharedDepEntry> SharedDepQueue;
@@ -114,7 +112,7 @@
                         cmTarget::LinkInterface const* iface,
                         bool follow_interface = false);
   void QueueSharedDependencies(int depender_index,
-                               std::vector<std::string> const& deps);
+                               std::vector<cmLinkItem> const& deps);
   void HandleSharedDependency(SharedDepEntry const& dep);
 
   // Dependency inferral for each link item.
@@ -165,7 +163,7 @@
 
   // Compatibility help.
   bool OldLinkDirMode;
-  void CheckWrongConfigItem(int depender_index, std::string const& item);
+  void CheckWrongConfigItem(cmLinkItem const& item);
   std::set<cmTarget const*> OldWrongConfigItems;
 };
 
diff --git a/Source/cmComputeLinkInformation.cxx b/Source/cmComputeLinkInformation.cxx
index ea8536f..e1852a3 100644
--- a/Source/cmComputeLinkInformation.cxx
+++ b/Source/cmComputeLinkInformation.cxx
@@ -239,12 +239,10 @@
 
 //----------------------------------------------------------------------------
 cmComputeLinkInformation
-::cmComputeLinkInformation(cmTarget const* target, const std::string& config,
-                           cmTarget const* headTarget)
+::cmComputeLinkInformation(cmTarget const* target, const std::string& config)
 {
   // Store context information.
   this->Target = target;
-  this->HeadTarget = headTarget;
   this->Makefile = this->Target->GetMakefile();
   this->LocalGenerator = this->Makefile->GetLocalGenerator();
   this->GlobalGenerator = this->LocalGenerator->GetGlobalGenerator();
@@ -267,7 +265,7 @@
   this->OrderDependentRPath = 0;
 
   // Get the language used for linking this target.
-  this->LinkLanguage = this->Target->GetLinkerLanguage(config, headTarget);
+  this->LinkLanguage = this->Target->GetLinkerLanguage(config);
   if(this->LinkLanguage.empty())
     {
     // The Compute method will do nothing, so skip the rest of the
@@ -505,8 +503,7 @@
     }
 
   // Compute the ordered link line items.
-  cmComputeLinkDepends cld(this->Target, this->Config,
-                           this->HeadTarget);
+  cmComputeLinkDepends cld(this->Target, this->Config);
   cld.SetOldLinkDirMode(this->OldLinkDirMode);
   cmComputeLinkDepends::EntryVector const& linkEntries = cld.Compute();
 
@@ -572,8 +569,7 @@
 void cmComputeLinkInformation::AddImplicitLinkInfo()
 {
   // The link closure lists all languages whose implicit info is needed.
-  cmTarget::LinkClosure const* lc=this->Target->GetLinkClosure(this->Config,
-                                                          this->HeadTarget);
+  cmTarget::LinkClosure const* lc=this->Target->GetLinkClosure(this->Config);
   for(std::vector<std::string>::const_iterator li = lc->Languages.begin();
       li != lc->Languages.end(); ++li)
     {
@@ -1811,7 +1807,7 @@
       }
     }
 
-  is_shared_library = this->ExtractSharedLibraryName.find(file.c_str());
+  is_shared_library = this->ExtractSharedLibraryName.find(file);
 
   if(!is_shared_library)
     {
@@ -1831,8 +1827,8 @@
     {
     if(fullPath.find(".framework") != std::string::npos)
       {
-      cmsys::RegularExpression splitFramework;
-      splitFramework.compile("^(.*)/(.*).framework/(.*)$");
+      static cmsys::RegularExpression
+        splitFramework("^(.*)/(.*).framework/(.*)$");
       if(splitFramework.find(fullPath) &&
         (std::string::npos !=
          splitFramework.match(3).find(splitFramework.match(2))))
@@ -1972,7 +1968,7 @@
   // present.  This is done even when skipping rpath support.
   {
   cmTarget::LinkClosure const* lc =
-    this->Target->GetLinkClosure(this->Config, this->HeadTarget);
+    this->Target->GetLinkClosure(this->Config);
   for(std::vector<std::string>::const_iterator li = lc->Languages.begin();
       li != lc->Languages.end(); ++li)
     {
diff --git a/Source/cmComputeLinkInformation.h b/Source/cmComputeLinkInformation.h
index e345fe2..e5d674a 100644
--- a/Source/cmComputeLinkInformation.h
+++ b/Source/cmComputeLinkInformation.h
@@ -29,8 +29,7 @@
 class cmComputeLinkInformation
 {
 public:
-  cmComputeLinkInformation(cmTarget const* target, const std::string& config,
-                           cmTarget const* headTarget);
+  cmComputeLinkInformation(cmTarget const* target, const std::string& config);
   ~cmComputeLinkInformation();
   bool Compute();
 
@@ -75,7 +74,6 @@
 
   // Context information.
   cmTarget const* Target;
-  cmTarget const* HeadTarget;
   cmMakefile* Makefile;
   cmLocalGenerator* LocalGenerator;
   cmGlobalGenerator* GlobalGenerator;
diff --git a/Source/cmComputeTargetDepends.cxx b/Source/cmComputeTargetDepends.cxx
index f28217f..75d3967 100644
--- a/Source/cmComputeTargetDepends.cxx
+++ b/Source/cmComputeTargetDepends.cxx
@@ -249,20 +249,21 @@
         const_cast<cmTarget*>(depender)->AddUtility(objLib);
         }
       }
-    std::vector<std::string> tlibs;
-    depender->GetDirectLinkLibraries(*it, tlibs, depender);
+
+    cmTarget::LinkImplementation const* impl =
+      depender->GetLinkImplementation(*it);
 
     // A target should not depend on itself.
     emitted.insert(depender->GetName());
-    for(std::vector<std::string>::const_iterator lib = tlibs.begin();
-        lib != tlibs.end(); ++lib)
+    for(std::vector<cmLinkImplItem>::const_iterator
+          lib = impl->Libraries.begin();
+        lib != impl->Libraries.end(); ++lib)
       {
       // Don't emit the same library twice for this target.
       if(emitted.insert(*lib).second)
         {
         this->AddTargetDepend(depender_index, *lib, true);
-        this->AddInterfaceDepends(depender_index, *lib,
-                                  true, emitted);
+        this->AddInterfaceDepends(depender_index, *lib, emitted);
         }
       }
     }
@@ -270,11 +271,11 @@
 
   // Loop over all utility dependencies.
   {
-  std::set<std::string> const& tutils = depender->GetUtilities();
+  std::set<cmLinkItem> const& tutils = depender->GetUtilityItems();
   std::set<std::string> emitted;
   // A target should not depend on itself.
   emitted.insert(depender->GetName());
-  for(std::set<std::string>::const_iterator util = tutils.begin();
+  for(std::set<cmLinkItem>::const_iterator util = tutils.begin();
       util != tutils.end(); ++util)
     {
     // Don't emit the same utility twice for this target.
@@ -296,7 +297,7 @@
   if(cmTarget::LinkInterface const* iface =
                                 dependee->GetLinkInterface(config, depender))
     {
-    for(std::vector<std::string>::const_iterator
+    for(std::vector<cmLinkItem>::const_iterator
         lib = iface->Libraries.begin();
         lib != iface->Libraries.end(); ++lib)
       {
@@ -304,8 +305,7 @@
       if(emitted.insert(*lib).second)
         {
         this->AddTargetDepend(depender_index, *lib, true);
-        this->AddInterfaceDepends(depender_index, *lib,
-                                  true, emitted);
+        this->AddInterfaceDepends(depender_index, *lib, emitted);
         }
       }
     }
@@ -313,17 +313,15 @@
 
 //----------------------------------------------------------------------------
 void cmComputeTargetDepends::AddInterfaceDepends(int depender_index,
-                                             const std::string& dependee_name,
-                                             bool linking,
+                                             cmLinkItem const& dependee_name,
                                              std::set<std::string> &emitted)
 {
   cmTarget const* depender = this->Targets[depender_index];
-  cmTarget const* dependee =
-    depender->GetMakefile()->FindTargetToUse(dependee_name);
+  cmTarget const* dependee = dependee_name.Target;
   // Skip targets that will not really be linked.  This is probably a
   // name conflict between an external library and an executable
   // within the project.
-  if(linking && dependee &&
+  if(dependee &&
      dependee->GetType() == cmTarget::EXECUTABLE &&
      !dependee->IsExecutableWithExports())
     {
@@ -347,16 +345,15 @@
 }
 
 //----------------------------------------------------------------------------
-void cmComputeTargetDepends::AddTargetDepend(int depender_index,
-                                             const std::string& dependee_name,
-                                             bool linking)
+void cmComputeTargetDepends::AddTargetDepend(
+  int depender_index, cmLinkItem const& dependee_name,
+  bool linking)
 {
   // Get the depender.
   cmTarget const* depender = this->Targets[depender_index];
 
   // Check the target's makefile first.
-  cmTarget const* dependee =
-    depender->GetMakefile()->FindTargetToUse(dependee_name);
+  cmTarget const* dependee = dependee_name.Target;
 
   if(!dependee && !linking &&
     (depender->GetType() != cmTarget::GLOBAL_TARGET))
@@ -424,12 +421,11 @@
   if(dependee->IsImported())
     {
     // Skip imported targets but follow their utility dependencies.
-    std::set<std::string> const& utils = dependee->GetUtilities();
-    for(std::set<std::string>::const_iterator i = utils.begin();
+    std::set<cmLinkItem> const& utils = dependee->GetUtilityItems();
+    for(std::set<cmLinkItem>::const_iterator i = utils.begin();
         i != utils.end(); ++i)
       {
-      if(cmTarget const* transitive_dependee =
-         dependee->GetMakefile()->FindTargetToUse(*i))
+      if(cmTarget const* transitive_dependee = i->Target)
         {
         this->AddTargetDepend(depender_index, transitive_dependee, false);
         }
diff --git a/Source/cmComputeTargetDepends.h b/Source/cmComputeTargetDepends.h
index 7553816..902f342 100644
--- a/Source/cmComputeTargetDepends.h
+++ b/Source/cmComputeTargetDepends.h
@@ -20,6 +20,7 @@
 
 class cmComputeComponentGraph;
 class cmGlobalGenerator;
+class cmLinkItem;
 class cmTarget;
 class cmTargetDependSet;
 
@@ -46,14 +47,14 @@
   void CollectDepends();
   void CollectTargetDepends(int depender_index);
   void AddTargetDepend(int depender_index,
-                       const std::string& dependee_name,
+                       cmLinkItem const& dependee_name,
                        bool linking);
   void AddTargetDepend(int depender_index, cmTarget const* dependee,
                        bool linking);
   bool ComputeFinalDepends(cmComputeComponentGraph const& ccg);
   void AddInterfaceDepends(int depender_index,
-                           const std::string& dependee_name,
-                           bool linking, std::set<std::string> &emitted);
+                           cmLinkItem const& dependee_name,
+                           std::set<std::string> &emitted);
   void AddInterfaceDepends(int depender_index, cmTarget const* dependee,
                            const std::string& config,
                            std::set<std::string> &emitted);
diff --git a/Source/cmConditionEvaluator.cxx b/Source/cmConditionEvaluator.cxx
new file mode 100644
index 0000000..aba26de
--- /dev/null
+++ b/Source/cmConditionEvaluator.cxx
@@ -0,0 +1,770 @@
+/*============================================================================
+  CMake - Cross Platform Makefile Generator
+  Copyright 2014 Kitware, Inc., Insight Software Consortium
+
+  Distributed under the OSI-approved BSD License (the "License");
+  see accompanying file Copyright.txt for details.
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the License for more information.
+============================================================================*/
+
+#include "cmConditionEvaluator.h"
+
+cmConditionEvaluator::cmConditionEvaluator(cmMakefile& makefile):
+  Makefile(makefile),
+  Policy12Status(makefile.GetPolicyStatus(cmPolicies::CMP0012)),
+  Policy54Status(makefile.GetPolicyStatus(cmPolicies::CMP0054))
+{
+
+}
+
+//=========================================================================
+// order of operations,
+// 1.   ( )   -- parenthetical groups
+// 2.  IS_DIRECTORY EXISTS COMMAND DEFINED etc predicates
+// 3. MATCHES LESS GREATER EQUAL STRLESS STRGREATER STREQUAL etc binary ops
+// 4. NOT
+// 5. AND OR
+//
+// There is an issue on whether the arguments should be values of references,
+// for example IF (FOO AND BAR) should that compare the strings FOO and BAR
+// or should it really do IF (${FOO} AND ${BAR}) Currently IS_DIRECTORY
+// EXISTS COMMAND and DEFINED all take values. EQUAL, LESS and GREATER can
+// take numeric values or variable names. STRLESS and STRGREATER take
+// variable names but if the variable name is not found it will use the name
+// directly. AND OR take variables or the values 0 or 1.
+
+bool cmConditionEvaluator::IsTrue(
+  const std::vector<cmExpandedCommandArgument> &args,
+  std::string &errorString,
+  cmake::MessageType &status)
+{
+  errorString = "";
+
+  // handle empty invocation
+  if (args.size() < 1)
+    {
+    return false;
+    }
+
+  // store the reduced args in this vector
+  cmArgumentList newArgs;
+
+  // copy to the list structure
+  for(unsigned int i = 0; i < args.size(); ++i)
+    {
+    newArgs.push_back(args[i]);
+    }
+
+  // now loop through the arguments and see if we can reduce any of them
+  // we do this multiple times. Once for each level of precedence
+  // parens
+  if (!this->HandleLevel0(newArgs, errorString, status))
+    {
+    return false;
+    }
+  //predicates
+  if (!this->HandleLevel1(newArgs, errorString, status))
+    {
+    return false;
+    }
+  // binary ops
+  if (!this->HandleLevel2(newArgs, errorString, status))
+    {
+    return false;
+    }
+
+  // NOT
+  if (!this->HandleLevel3(newArgs, errorString, status))
+    {
+    return false;
+    }
+  // AND OR
+  if (!this->HandleLevel4(newArgs, errorString, status))
+    {
+    return false;
+    }
+
+  // now at the end there should only be one argument left
+  if (newArgs.size() != 1)
+    {
+    errorString = "Unknown arguments specified";
+    status = cmake::FATAL_ERROR;
+    return false;
+    }
+
+  return this->GetBooleanValueWithAutoDereference(*(newArgs.begin()),
+    errorString, status, true);
+}
+
+//=========================================================================
+const char* cmConditionEvaluator::GetDefinitionIfUnquoted(
+  cmExpandedCommandArgument const& argument) const
+{
+  if((this->Policy54Status != cmPolicies::WARN &&
+     this->Policy54Status != cmPolicies::OLD) &&
+     argument.WasQuoted())
+    {
+    return 0;
+    }
+
+  const char* def = this->Makefile.GetDefinition(argument.GetValue());
+
+  if(def && argument.WasQuoted() && this->Policy54Status == cmPolicies::WARN)
+    {
+    bool hasBeenReported = this->Makefile.HasCMP0054AlreadyBeenReported(
+      this->Makefile.GetBacktrace()[0]);
+
+    if(!hasBeenReported)
+      {
+      cmOStringStream e;
+      e << (this->Makefile.GetPolicies()->GetPolicyWarning(
+        cmPolicies::CMP0054)) << "\n";
+      e << "Quoted variables like \"" << argument.GetValue() <<
+        "\" will no longer be dereferenced "
+        "when the policy is set to NEW.  "
+        "Since the policy is not set the OLD behavior will be used.";
+
+      this->Makefile.IssueMessage(cmake::AUTHOR_WARNING, e.str());
+      }
+    }
+
+  return def;
+}
+
+//=========================================================================
+const char* cmConditionEvaluator::GetVariableOrString(
+    const cmExpandedCommandArgument& argument) const
+{
+  const char* def = this->GetDefinitionIfUnquoted(argument);
+
+  if(!def)
+    {
+    def = argument.c_str();
+    }
+
+  return def;
+}
+
+//=========================================================================
+bool cmConditionEvaluator::IsKeyword(std::string const& keyword,
+  cmExpandedCommandArgument& argument) const
+{
+  if((this->Policy54Status != cmPolicies::WARN &&
+     this->Policy54Status != cmPolicies::OLD) &&
+     argument.WasQuoted())
+    {
+    return false;
+    }
+
+  bool isKeyword = argument.GetValue() == keyword;
+
+  if(isKeyword && argument.WasQuoted() &&
+    this->Policy54Status == cmPolicies::WARN)
+    {
+    bool hasBeenReported = this->Makefile.HasCMP0054AlreadyBeenReported(
+      this->Makefile.GetBacktrace()[0]);
+
+    if(!hasBeenReported)
+      {
+      cmOStringStream e;
+      e << (this->Makefile.GetPolicies()->GetPolicyWarning(
+        cmPolicies::CMP0054)) << "\n";
+      e << "Quoted keywords like \"" << argument.GetValue() <<
+        "\" will no longer be interpreted as keywords "
+        "when the policy is set to NEW.  "
+        "Since the policy is not set the OLD behavior will be used.";
+
+      this->Makefile.IssueMessage(cmake::AUTHOR_WARNING, e.str());
+      }
+    }
+
+  return isKeyword;
+}
+
+//=========================================================================
+bool cmConditionEvaluator::GetBooleanValue(
+  cmExpandedCommandArgument& arg) const
+{
+  // Check basic constants.
+  if (arg == "0")
+    {
+    return false;
+    }
+  if (arg == "1")
+    {
+    return true;
+    }
+
+  // Check named constants.
+  if (cmSystemTools::IsOn(arg.c_str()))
+    {
+    return true;
+    }
+  if (cmSystemTools::IsOff(arg.c_str()))
+    {
+    return false;
+    }
+
+  // Check for numbers.
+  if(!arg.empty())
+    {
+    char* end;
+    double d = strtod(arg.c_str(), &end);
+    if(*end == '\0')
+      {
+      // The whole string is a number.  Use C conversion to bool.
+      return d? true:false;
+      }
+    }
+
+  // Check definition.
+  const char* def = this->GetDefinitionIfUnquoted(arg);
+  return !cmSystemTools::IsOff(def);
+}
+
+//=========================================================================
+// Boolean value behavior from CMake 2.6.4 and below.
+bool cmConditionEvaluator::GetBooleanValueOld(
+  cmExpandedCommandArgument const& arg, bool one) const
+{
+  if(one)
+    {
+    // Old IsTrue behavior for single argument.
+    if(arg == "0")
+      { return false; }
+    else if(arg == "1")
+      { return true; }
+    else
+      {
+      const char* def = this->GetDefinitionIfUnquoted(arg);
+      return !cmSystemTools::IsOff(def);
+      }
+    }
+  else
+    {
+    // Old GetVariableOrNumber behavior.
+    const char* def = this->GetDefinitionIfUnquoted(arg);
+    if(!def && atoi(arg.c_str()))
+      {
+      def = arg.c_str();
+      }
+    return !cmSystemTools::IsOff(def);
+    }
+}
+
+//=========================================================================
+// returns the resulting boolean value
+bool cmConditionEvaluator::GetBooleanValueWithAutoDereference(
+  cmExpandedCommandArgument &newArg,
+  std::string &errorString,
+  cmake::MessageType &status,
+  bool oneArg) const
+{
+  // Use the policy if it is set.
+  if (this->Policy12Status == cmPolicies::NEW)
+    {
+    return GetBooleanValue(newArg);
+    }
+  else if (this->Policy12Status == cmPolicies::OLD)
+    {
+    return GetBooleanValueOld(newArg, oneArg);
+    }
+
+  // Check policy only if old and new results differ.
+  bool newResult = this->GetBooleanValue(newArg);
+  bool oldResult = this->GetBooleanValueOld(newArg, oneArg);
+  if(newResult != oldResult)
+    {
+    switch(this->Policy12Status)
+      {
+      case cmPolicies::WARN:
+        {
+        cmPolicies* policies = this->Makefile.GetPolicies();
+        errorString = "An argument named \"" + newArg.GetValue()
+          + "\" appears in a conditional statement.  "
+          + policies->GetPolicyWarning(cmPolicies::CMP0012);
+        status = cmake::AUTHOR_WARNING;
+        }
+      case cmPolicies::OLD:
+        return oldResult;
+      case cmPolicies::REQUIRED_IF_USED:
+      case cmPolicies::REQUIRED_ALWAYS:
+        {
+        cmPolicies* policies = this->Makefile.GetPolicies();
+        errorString = "An argument named \"" + newArg.GetValue()
+          + "\" appears in a conditional statement.  "
+          + policies->GetRequiredPolicyError(cmPolicies::CMP0012);
+        status = cmake::FATAL_ERROR;
+        }
+      case cmPolicies::NEW:
+        break;
+      }
+    }
+  return newResult;
+}
+
+//=========================================================================
+void cmConditionEvaluator::IncrementArguments(cmArgumentList &newArgs,
+                        cmArgumentList::iterator &argP1,
+                        cmArgumentList::iterator &argP2) const
+{
+  if (argP1  != newArgs.end())
+    {
+    argP1++;
+    argP2 = argP1;
+    if (argP1  != newArgs.end())
+      {
+      argP2++;
+      }
+    }
+}
+
+//=========================================================================
+// helper function to reduce code duplication
+void cmConditionEvaluator::HandlePredicate(bool value, int &reducible,
+                     cmArgumentList::iterator &arg,
+                     cmArgumentList &newArgs,
+                     cmArgumentList::iterator &argP1,
+                     cmArgumentList::iterator &argP2) const
+{
+  if(value)
+    {
+    *arg = cmExpandedCommandArgument("1", true);
+    }
+  else
+    {
+    *arg = cmExpandedCommandArgument("0", true);
+    }
+  newArgs.erase(argP1);
+  argP1 = arg;
+  this->IncrementArguments(newArgs,argP1,argP2);
+  reducible = 1;
+}
+
+//=========================================================================
+// helper function to reduce code duplication
+void cmConditionEvaluator::HandleBinaryOp(bool value, int &reducible,
+                     cmArgumentList::iterator &arg,
+                     cmArgumentList &newArgs,
+                     cmArgumentList::iterator &argP1,
+                     cmArgumentList::iterator &argP2)
+{
+  if(value)
+    {
+    *arg = cmExpandedCommandArgument("1", true);
+    }
+  else
+    {
+    *arg = cmExpandedCommandArgument("0", true);
+    }
+  newArgs.erase(argP2);
+  newArgs.erase(argP1);
+  argP1 = arg;
+  this->IncrementArguments(newArgs,argP1,argP2);
+  reducible = 1;
+}
+
+//=========================================================================
+// level 0 processes parenthetical expressions
+bool cmConditionEvaluator::HandleLevel0(cmArgumentList &newArgs,
+                  std::string &errorString,
+                  cmake::MessageType &status)
+{
+  int reducible;
+  do
+    {
+    reducible = 0;
+    cmArgumentList::iterator arg = newArgs.begin();
+    while (arg != newArgs.end())
+      {
+      if (IsKeyword("(", *arg))
+        {
+        // search for the closing paren for this opening one
+        cmArgumentList::iterator argClose;
+        argClose = arg;
+        argClose++;
+        unsigned int depth = 1;
+        while (argClose != newArgs.end() && depth)
+          {
+          if (this->IsKeyword("(", *argClose))
+            {
+              depth++;
+            }
+          if (this->IsKeyword(")", *argClose))
+            {
+              depth--;
+            }
+          argClose++;
+          }
+        if (depth)
+          {
+          errorString = "mismatched parenthesis in condition";
+          status = cmake::FATAL_ERROR;
+          return false;
+          }
+        // store the reduced args in this vector
+        std::vector<cmExpandedCommandArgument> newArgs2;
+
+        // copy to the list structure
+        cmArgumentList::iterator argP1 = arg;
+        argP1++;
+        for(; argP1 != argClose; argP1++)
+          {
+          newArgs2.push_back(*argP1);
+          }
+        newArgs2.pop_back();
+        // now recursively invoke IsTrue to handle the values inside the
+        // parenthetical expression
+        bool value =
+          this->IsTrue(newArgs2, errorString, status);
+        if(value)
+          {
+          *arg = cmExpandedCommandArgument("1", true);
+          }
+        else
+          {
+          *arg = cmExpandedCommandArgument("0", true);
+          }
+        argP1 = arg;
+        argP1++;
+        // remove the now evaluated parenthetical expression
+        newArgs.erase(argP1,argClose);
+        }
+      ++arg;
+      }
+    }
+  while (reducible);
+  return true;
+}
+
+//=========================================================================
+// level one handles most predicates except for NOT
+bool cmConditionEvaluator::HandleLevel1(cmArgumentList &newArgs,
+                  std::string &, cmake::MessageType &)
+{
+  int reducible;
+  do
+    {
+    reducible = 0;
+    cmArgumentList::iterator arg = newArgs.begin();
+    cmArgumentList::iterator argP1;
+    cmArgumentList::iterator argP2;
+    while (arg != newArgs.end())
+      {
+      argP1 = arg;
+      this->IncrementArguments(newArgs,argP1,argP2);
+      // does a file exist
+      if (this->IsKeyword("EXISTS", *arg) && argP1  != newArgs.end())
+        {
+        this->HandlePredicate(
+          cmSystemTools::FileExists(argP1->c_str()),
+          reducible, arg, newArgs, argP1, argP2);
+        }
+      // does a directory with this name exist
+      if (this->IsKeyword("IS_DIRECTORY", *arg) && argP1  != newArgs.end())
+        {
+        this->HandlePredicate(
+          cmSystemTools::FileIsDirectory(argP1->c_str()),
+          reducible, arg, newArgs, argP1, argP2);
+        }
+      // does a symlink with this name exist
+      if (this->IsKeyword("IS_SYMLINK", *arg) && argP1  != newArgs.end())
+        {
+        this->HandlePredicate(
+          cmSystemTools::FileIsSymlink(argP1->c_str()),
+          reducible, arg, newArgs, argP1, argP2);
+        }
+      // is the given path an absolute path ?
+      if (this->IsKeyword("IS_ABSOLUTE", *arg) && argP1  != newArgs.end())
+        {
+        this->HandlePredicate(
+          cmSystemTools::FileIsFullPath(argP1->c_str()),
+          reducible, arg, newArgs, argP1, argP2);
+        }
+      // does a command exist
+      if (this->IsKeyword("COMMAND", *arg) && argP1  != newArgs.end())
+        {
+        this->HandlePredicate(
+          this->Makefile.CommandExists(argP1->c_str()),
+          reducible, arg, newArgs, argP1, argP2);
+        }
+      // does a policy exist
+      if (this->IsKeyword("POLICY", *arg) && argP1 != newArgs.end())
+        {
+        cmPolicies::PolicyID pid;
+        this->HandlePredicate(
+          this->Makefile.GetPolicies()->GetPolicyID(
+            argP1->c_str(), pid),
+            reducible, arg, newArgs, argP1, argP2);
+        }
+      // does a target exist
+      if (this->IsKeyword("TARGET", *arg) && argP1 != newArgs.end())
+        {
+        this->HandlePredicate(
+          this->Makefile.FindTargetToUse(argP1->GetValue())?true:false,
+          reducible, arg, newArgs, argP1, argP2);
+        }
+      // is a variable defined
+      if (this->IsKeyword("DEFINED", *arg) && argP1  != newArgs.end())
+        {
+        size_t argP1len = argP1->GetValue().size();
+        bool bdef = false;
+        if(argP1len > 4 && argP1->GetValue().substr(0, 4) == "ENV{" &&
+           argP1->GetValue().operator[](argP1len-1) == '}')
+          {
+          std::string env = argP1->GetValue().substr(4, argP1len-5);
+          bdef = cmSystemTools::GetEnv(env.c_str())?true:false;
+          }
+        else
+          {
+          bdef = this->Makefile.IsDefinitionSet(argP1->GetValue());
+          }
+        this->HandlePredicate(bdef, reducible, arg, newArgs, argP1, argP2);
+        }
+      ++arg;
+      }
+    }
+  while (reducible);
+  return true;
+}
+
+//=========================================================================
+// level two handles most binary operations except for AND  OR
+bool cmConditionEvaluator::HandleLevel2(cmArgumentList &newArgs,
+                  std::string &errorString,
+                  cmake::MessageType &status)
+{
+  int reducible;
+  const char *def;
+  const char *def2;
+  do
+    {
+    reducible = 0;
+    cmArgumentList::iterator arg = newArgs.begin();
+    cmArgumentList::iterator argP1;
+    cmArgumentList::iterator argP2;
+    while (arg != newArgs.end())
+      {
+      argP1 = arg;
+      this->IncrementArguments(newArgs,argP1,argP2);
+      if (argP1 != newArgs.end() && argP2 != newArgs.end() &&
+        IsKeyword("MATCHES", *argP1))
+        {
+        def = this->GetVariableOrString(*arg);
+        const char* rex = argP2->c_str();
+        this->Makefile.ClearMatches();
+        cmsys::RegularExpression regEntry;
+        if ( !regEntry.compile(rex) )
+          {
+          cmOStringStream error;
+          error << "Regular expression \"" << rex << "\" cannot compile";
+          errorString = error.str();
+          status = cmake::FATAL_ERROR;
+          return false;
+          }
+        if (regEntry.find(def))
+          {
+          this->Makefile.StoreMatches(regEntry);
+          *arg = cmExpandedCommandArgument("1", true);
+          }
+        else
+          {
+          *arg = cmExpandedCommandArgument("0", true);
+          }
+        newArgs.erase(argP2);
+        newArgs.erase(argP1);
+        argP1 = arg;
+        this->IncrementArguments(newArgs,argP1,argP2);
+        reducible = 1;
+        }
+
+      if (argP1 != newArgs.end() && this->IsKeyword("MATCHES", *arg))
+        {
+        *arg = cmExpandedCommandArgument("0", true);
+        newArgs.erase(argP1);
+        argP1 = arg;
+        this->IncrementArguments(newArgs,argP1,argP2);
+        reducible = 1;
+        }
+
+      if (argP1 != newArgs.end() && argP2 != newArgs.end() &&
+        (this->IsKeyword("LESS", *argP1) ||
+         this->IsKeyword("GREATER", *argP1) ||
+         this->IsKeyword("EQUAL", *argP1)))
+        {
+        def = this->GetVariableOrString(*arg);
+        def2 = this->GetVariableOrString(*argP2);
+        double lhs;
+        double rhs;
+        bool result;
+        if(sscanf(def, "%lg", &lhs) != 1 ||
+           sscanf(def2, "%lg", &rhs) != 1)
+          {
+          result = false;
+          }
+        else if (*(argP1) == "LESS")
+          {
+          result = (lhs < rhs);
+          }
+        else if (*(argP1) == "GREATER")
+          {
+          result = (lhs > rhs);
+          }
+        else
+          {
+          result = (lhs == rhs);
+          }
+        this->HandleBinaryOp(result,
+          reducible, arg, newArgs, argP1, argP2);
+        }
+
+      if (argP1 != newArgs.end() && argP2 != newArgs.end() &&
+        (this->IsKeyword("STRLESS", *argP1) ||
+         this->IsKeyword("STREQUAL", *argP1) ||
+         this->IsKeyword("STRGREATER", *argP1)))
+        {
+        def = this->GetVariableOrString(*arg);
+        def2 = this->GetVariableOrString(*argP2);
+        int val = strcmp(def,def2);
+        bool result;
+        if (*(argP1) == "STRLESS")
+          {
+          result = (val < 0);
+          }
+        else if (*(argP1) == "STRGREATER")
+          {
+          result = (val > 0);
+          }
+        else // strequal
+          {
+          result = (val == 0);
+          }
+        this->HandleBinaryOp(result,
+          reducible, arg, newArgs, argP1, argP2);
+        }
+
+      if (argP1 != newArgs.end() && argP2 != newArgs.end() &&
+        (this->IsKeyword("VERSION_LESS", *argP1) ||
+         this->IsKeyword("VERSION_GREATER", *argP1) ||
+         this->IsKeyword("VERSION_EQUAL", *argP1)))
+        {
+        def = this->GetVariableOrString(*arg);
+        def2 = this->GetVariableOrString(*argP2);
+        cmSystemTools::CompareOp op = cmSystemTools::OP_EQUAL;
+        if(*argP1 == "VERSION_LESS")
+          {
+          op = cmSystemTools::OP_LESS;
+          }
+        else if(*argP1 == "VERSION_GREATER")
+          {
+          op = cmSystemTools::OP_GREATER;
+          }
+        bool result = cmSystemTools::VersionCompare(op, def, def2);
+        this->HandleBinaryOp(result,
+          reducible, arg, newArgs, argP1, argP2);
+        }
+
+      // is file A newer than file B
+      if (argP1 != newArgs.end() && argP2 != newArgs.end() &&
+          this->IsKeyword("IS_NEWER_THAN", *argP1))
+        {
+        int fileIsNewer=0;
+        bool success=cmSystemTools::FileTimeCompare(arg->GetValue(),
+            (argP2)->GetValue(),
+            &fileIsNewer);
+        this->HandleBinaryOp(
+          (success==false || fileIsNewer==1 || fileIsNewer==0),
+          reducible, arg, newArgs, argP1, argP2);
+        }
+
+      ++arg;
+      }
+    }
+  while (reducible);
+  return true;
+}
+
+//=========================================================================
+// level 3 handles NOT
+bool cmConditionEvaluator::HandleLevel3(cmArgumentList &newArgs,
+                  std::string &errorString,
+                  cmake::MessageType &status)
+{
+  int reducible;
+  do
+    {
+    reducible = 0;
+    cmArgumentList::iterator arg = newArgs.begin();
+    cmArgumentList::iterator argP1;
+    cmArgumentList::iterator argP2;
+    while (arg != newArgs.end())
+      {
+      argP1 = arg;
+      IncrementArguments(newArgs,argP1,argP2);
+      if (argP1 != newArgs.end() && IsKeyword("NOT", *arg))
+        {
+        bool rhs = this->GetBooleanValueWithAutoDereference(*argP1,
+                                                      errorString,
+                                                      status);
+        this->HandlePredicate(!rhs, reducible, arg, newArgs, argP1, argP2);
+        }
+      ++arg;
+      }
+    }
+  while (reducible);
+  return true;
+}
+
+//=========================================================================
+// level 4 handles AND OR
+bool cmConditionEvaluator::HandleLevel4(cmArgumentList &newArgs,
+                  std::string &errorString,
+                  cmake::MessageType &status)
+{
+  int reducible;
+  bool lhs;
+  bool rhs;
+  do
+    {
+    reducible = 0;
+    cmArgumentList::iterator arg = newArgs.begin();
+    cmArgumentList::iterator argP1;
+    cmArgumentList::iterator argP2;
+    while (arg != newArgs.end())
+      {
+      argP1 = arg;
+      IncrementArguments(newArgs,argP1,argP2);
+      if (argP1 != newArgs.end() && IsKeyword("AND", *argP1) &&
+        argP2 != newArgs.end())
+        {
+        lhs = this->GetBooleanValueWithAutoDereference(*arg,
+                                                 errorString,
+                                                 status);
+        rhs = this->GetBooleanValueWithAutoDereference(*argP2,
+                                                 errorString,
+                                                 status);
+        this->HandleBinaryOp((lhs && rhs),
+          reducible, arg, newArgs, argP1, argP2);
+        }
+
+      if (argP1 != newArgs.end() && this->IsKeyword("OR", *argP1) &&
+        argP2 != newArgs.end())
+        {
+        lhs = this->GetBooleanValueWithAutoDereference(*arg,
+                                                 errorString,
+                                                 status);
+        rhs = this->GetBooleanValueWithAutoDereference(*argP2,
+                                                 errorString,
+                                                 status);
+        this->HandleBinaryOp((lhs || rhs),
+          reducible, arg, newArgs, argP1, argP2);
+        }
+      ++arg;
+      }
+    }
+  while (reducible);
+  return true;
+}
diff --git a/Source/cmConditionEvaluator.h b/Source/cmConditionEvaluator.h
new file mode 100644
index 0000000..01624f9
--- /dev/null
+++ b/Source/cmConditionEvaluator.h
@@ -0,0 +1,96 @@
+/*============================================================================
+  CMake - Cross Platform Makefile Generator
+  Copyright 2014 Kitware, Inc., Insight Software Consortium
+
+  Distributed under the OSI-approved BSD License (the "License");
+  see accompanying file Copyright.txt for details.
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the License for more information.
+============================================================================*/
+#ifndef cmConditionEvaluator_h
+#define cmConditionEvaluator_h
+
+#include "cmCommand.h"
+#include "cmExpandedCommandArgument.h"
+
+class cmConditionEvaluator
+{
+public:
+  typedef std::list<cmExpandedCommandArgument> cmArgumentList;
+
+  cmConditionEvaluator(cmMakefile& makefile);
+
+  // this is a shared function for both If and Else to determine if the
+  // arguments were valid, and if so, was the response true. If there is
+  // an error, the errorString will be set.
+  bool IsTrue(const std::vector<cmExpandedCommandArgument> &args,
+      std::string &errorString,
+      cmake::MessageType &status);
+
+private:
+  // Filter the given variable definition based on policy CMP0054.
+  const char* GetDefinitionIfUnquoted(
+      const cmExpandedCommandArgument& argument) const;
+
+  const char* GetVariableOrString(
+      const cmExpandedCommandArgument& argument) const;
+
+  bool IsKeyword(std::string const& keyword,
+    cmExpandedCommandArgument& argument) const;
+
+  bool GetBooleanValue(
+    cmExpandedCommandArgument& arg) const;
+
+  bool GetBooleanValueOld(
+    cmExpandedCommandArgument const& arg, bool one) const;
+
+  bool GetBooleanValueWithAutoDereference(
+    cmExpandedCommandArgument &newArg,
+    std::string &errorString,
+    cmake::MessageType &status,
+    bool oneArg = false) const;
+
+  void IncrementArguments(
+    cmArgumentList &newArgs,
+    cmArgumentList::iterator &argP1,
+    cmArgumentList::iterator &argP2) const;
+
+  void HandlePredicate(bool value, int &reducible,
+     cmArgumentList::iterator &arg,
+     cmArgumentList &newArgs,
+     cmArgumentList::iterator &argP1,
+     cmArgumentList::iterator &argP2) const;
+
+  void HandleBinaryOp(bool value, int &reducible,
+     cmArgumentList::iterator &arg,
+     cmArgumentList &newArgs,
+     cmArgumentList::iterator &argP1,
+     cmArgumentList::iterator &argP2);
+
+  bool HandleLevel0(cmArgumentList &newArgs,
+      std::string &errorString,
+      cmake::MessageType &status);
+
+  bool HandleLevel1(cmArgumentList &newArgs,
+      std::string &, cmake::MessageType &);
+
+  bool HandleLevel2(cmArgumentList &newArgs,
+      std::string &errorString,
+      cmake::MessageType &status);
+
+  bool HandleLevel3(cmArgumentList &newArgs,
+      std::string &errorString,
+      cmake::MessageType &status);
+
+  bool HandleLevel4(cmArgumentList &newArgs,
+      std::string &errorString,
+      cmake::MessageType &status);
+
+  cmMakefile& Makefile;
+  cmPolicies::PolicyStatus Policy12Status;
+  cmPolicies::PolicyStatus Policy54Status;
+};
+
+#endif
diff --git a/Source/cmCoreTryCompile.cxx b/Source/cmCoreTryCompile.cxx
index a3f3277..bc5708d 100644
--- a/Source/cmCoreTryCompile.cxx
+++ b/Source/cmCoreTryCompile.cxx
@@ -489,7 +489,7 @@
                                        targetName,
                                        this->SrcFileSignature,
                                        &cmakeFlags,
-                                       &output);
+                                       output);
   if ( erroroc )
     {
     cmSystemTools::SetErrorOccured();
@@ -634,6 +634,10 @@
     searchDirs.push_back(tmp);
     }
   searchDirs.push_back("/Debug");
+#if defined(__APPLE__)
+  std::string app = "/Debug/" + targetName + ".app";
+  searchDirs.push_back(app);
+#endif
   searchDirs.push_back("/Development");
 
   for(std::vector<std::string>::const_iterator it = searchDirs.begin();
diff --git a/Source/cmDefinitions.cxx b/Source/cmDefinitions.cxx
index babf1c4..fe32dd5 100644
--- a/Source/cmDefinitions.cxx
+++ b/Source/cmDefinitions.cxx
@@ -15,7 +15,8 @@
 cmDefinitions::Def cmDefinitions::NoDef;
 
 //----------------------------------------------------------------------------
-cmDefinitions::cmDefinitions(cmDefinitions* parent): Up(parent)
+cmDefinitions::cmDefinitions(cmDefinitions* parent)
+  : Up(parent)
 {
 }
 
@@ -35,7 +36,7 @@
     {
     return i->second;
     }
-  else if(cmDefinitions* up = this->Up)
+  if(cmDefinitions* up = this->Up)
     {
     // Query the parent scope and store the result locally.
     Def def = up->GetInternal(key);
@@ -51,16 +52,7 @@
   if(this->Up || def.Exists)
     {
     // In lower scopes we store keys, defined or not.
-    MapType::iterator i = this->Map.find(key);
-    if(i == this->Map.end())
-      {
-      i = this->Map.insert(MapType::value_type(key, def)).first;
-      }
-    else
-      {
-      i->second = def;
-      }
-    return i->second;
+    return (this->Map[key] = def);
     }
   else
     {
diff --git a/Source/cmDefinitions.h b/Source/cmDefinitions.h
index d615fb0..a2f053f 100644
--- a/Source/cmDefinitions.h
+++ b/Source/cmDefinitions.h
@@ -13,6 +13,9 @@
 #define cmDefinitions_h
 
 #include "cmStandardIncludes.h"
+#if defined(CMAKE_BUILD_WITH_CMAKE)
+#include "cmsys/hash_map.hxx"
+#endif
 
 /** \class cmDefinitions
  * \brief Store a scope of variable definitions for CMake language.
@@ -69,7 +72,11 @@
   cmDefinitions* Up;
 
   // Local definitions, set or unset.
+#if defined(CMAKE_BUILD_WITH_CMAKE)
+  typedef cmsys::hash_map<std::string, Def> MapType;
+#else
   typedef std::map<std::string, Def> MapType;
+#endif
   MapType Map;
 
   // Internal query and update methods.
diff --git a/Source/cmDepends.cxx b/Source/cmDepends.cxx
index 50a395e..134f45b 100644
--- a/Source/cmDepends.cxx
+++ b/Source/cmDepends.cxx
@@ -58,12 +58,7 @@
     // Get the source and object file.
     std::string const& src = *si++;
     if(si == pairs.end()) { break; }
-    std::string obj = *si++;
-
-    // Make sure the object file is relative to the top of the build tree.
-    obj = this->LocalGenerator->Convert(obj,
-                                        cmLocalGenerator::HOME_OUTPUT,
-                                        cmLocalGenerator::MAKEFILE);
+    std::string const& obj = *si++;
     dependencies[obj].insert(src);
     }
   for(std::map<std::string, std::set<std::string> >::const_iterator
diff --git a/Source/cmDependsC.cxx b/Source/cmDependsC.cxx
index d26d3a9..a1fc268 100644
--- a/Source/cmDependsC.cxx
+++ b/Source/cmDependsC.cxx
@@ -269,14 +269,20 @@
   // written by the original local generator for this directory
   // convert the dependencies to paths relative to the home output
   // directory.  We must do the same here.
-  internalDepends << obj << std::endl;
+  std::string obj_i =
+    this->LocalGenerator->Convert(obj, cmLocalGenerator::HOME_OUTPUT);
+  std::string obj_m =
+    this->LocalGenerator->ConvertToOutputFormat(obj_i,
+                                                cmLocalGenerator::MAKERULE);
+  internalDepends << obj_i << std::endl;
+
   for(std::set<std::string>::const_iterator i=dependencies.begin();
       i != dependencies.end(); ++i)
     {
-    makeDepends << obj << ": " <<
+    makeDepends << obj_m << ": " <<
       this->LocalGenerator->Convert(*i,
                                     cmLocalGenerator::HOME_OUTPUT,
-                                    cmLocalGenerator::MAKEFILE)
+                                    cmLocalGenerator::MAKERULE)
                 << std::endl;
     internalDepends << " " << *i << std::endl;
     }
diff --git a/Source/cmDependsFortran.cxx b/Source/cmDependsFortran.cxx
index 79cb560..8fc8347 100644
--- a/Source/cmDependsFortran.cxx
+++ b/Source/cmDependsFortran.cxx
@@ -443,15 +443,20 @@
   const char* src = info.Source.c_str();
 
   // Write the include dependencies to the output stream.
-  internalDepends << obj << std::endl;
+  std::string obj_i =
+    this->LocalGenerator->Convert(obj, cmLocalGenerator::HOME_OUTPUT);
+  std::string obj_m =
+    this->LocalGenerator->ConvertToOutputFormat(obj_i,
+                                                cmLocalGenerator::MAKERULE);
+  internalDepends << obj_i << std::endl;
   internalDepends << " " << src << std::endl;
   for(std::set<std::string>::const_iterator i = info.Includes.begin();
       i != info.Includes.end(); ++i)
     {
-    makeDepends << obj << ": " <<
+    makeDepends << obj_m << ": " <<
       this->LocalGenerator->Convert(*i,
                                     cmLocalGenerator::HOME_OUTPUT,
-                                    cmLocalGenerator::MAKEFILE)
+                                    cmLocalGenerator::MAKERULE)
                 << std::endl;
     internalDepends << " " << *i << std::endl;
     }
@@ -482,10 +487,10 @@
       proxy += ".mod.proxy";
       proxy = this->LocalGenerator->Convert(proxy,
                                             cmLocalGenerator::HOME_OUTPUT,
-                                            cmLocalGenerator::MAKEFILE);
+                                            cmLocalGenerator::MAKERULE);
 
       // since we require some things add them to our list of requirements
-      makeDepends << obj << ".requires: " << proxy << std::endl;
+      makeDepends << obj_m << ".requires: " << proxy << std::endl;
       }
 
     // The object file should depend on timestamped files for the
@@ -499,8 +504,8 @@
       std::string stampFile =
         this->LocalGenerator->Convert(required->second,
                                       cmLocalGenerator::HOME_OUTPUT,
-                                      cmLocalGenerator::MAKEFILE);
-      makeDepends << obj << ": " << stampFile << "\n";
+                                      cmLocalGenerator::MAKERULE);
+      makeDepends << obj_m << ": " << stampFile << "\n";
       }
     else
       {
@@ -512,8 +517,8 @@
         module =
           this->LocalGenerator->Convert(module,
                                         cmLocalGenerator::HOME_OUTPUT,
-                                        cmLocalGenerator::MAKEFILE);
-        makeDepends << obj << ": " << module << "\n";
+                                        cmLocalGenerator::MAKERULE);
+        makeDepends << obj_m << ": " << module << "\n";
         }
       }
     }
@@ -528,8 +533,8 @@
     proxy += ".mod.proxy";
     proxy = this->LocalGenerator->Convert(proxy,
                                           cmLocalGenerator::HOME_OUTPUT,
-                                          cmLocalGenerator::MAKEFILE);
-    makeDepends << proxy << ": " << obj << ".provides" << std::endl;
+                                          cmLocalGenerator::MAKERULE);
+    makeDepends << proxy << ": " << obj_m << ".provides" << std::endl;
     }
 
   // If any modules are provided then they must be converted to stamp files.
@@ -537,7 +542,7 @@
     {
     // Create a target to copy the module after the object file
     // changes.
-    makeDepends << obj << ".provides.build:\n";
+    makeDepends << obj_m << ".provides.build:\n";
     for(std::set<std::string>::const_iterator i = info.Provides.begin();
         i != info.Provides.end(); ++i)
       {
@@ -575,7 +580,7 @@
       }
     // After copying the modules update the timestamp file so that
     // copying will not be done again until the source rebuilds.
-    makeDepends << "\t$(CMAKE_COMMAND) -E touch " << obj
+    makeDepends << "\t$(CMAKE_COMMAND) -E touch " << obj_m
                 << ".provides.build\n";
 
     // Make sure the module timestamp rule is evaluated by the time
@@ -584,8 +589,8 @@
     driver += "/build";
     driver = this->LocalGenerator->Convert(driver,
                                            cmLocalGenerator::HOME_OUTPUT,
-                                           cmLocalGenerator::MAKEFILE);
-    makeDepends << driver << ": " << obj << ".provides.build\n";
+                                           cmLocalGenerator::MAKERULE);
+    makeDepends << driver << ": " << obj_m << ".provides.build\n";
     }
 
   return true;
@@ -765,7 +770,11 @@
                                      const char* compilerId)
 {
   /*
-  gnu:
+  gnu >= 4.9:
+    A mod file is an ascii file compressed with gzip.
+    Compiling twice produces identical modules.
+
+  gnu < 4.9:
     A mod file is an ascii file.
     <bar.mod>
     FORTRAN module created from /path/to/foo.f90 on Sun Dec 30 22:47:58 2007
@@ -821,21 +830,30 @@
    */
   if (strcmp(compilerId, "GNU") == 0 )
     {
-    const char seq[1] = {'\n'};
-    const int seqlen = 1;
-
-    if(!cmDependsFortranStreamContainsSequence(finModFile, seq, seqlen))
+    // GNU Fortran 4.9 and later compress .mod files with gzip
+    // but also do not include a date so we can fall through to
+    // compare them without skipping any prefix.
+    unsigned char hdr[2];
+    bool okay = finModFile.read(reinterpret_cast<char*>(hdr), 2)? true:false;
+    finModFile.seekg(0);
+    if(!(okay && hdr[0] == 0x1f && hdr[1] == 0x8b))
       {
-      // The module is of unexpected format.  Assume it is different.
-      std::cerr << compilerId << " fortran module " << modFile
-                << " has unexpected format." << std::endl;
-      return true;
-      }
+      const char seq[1] = {'\n'};
+      const int seqlen = 1;
 
-    if(!cmDependsFortranStreamContainsSequence(finStampFile, seq, seqlen))
-      {
-      // The stamp must differ if the sequence is not contained.
-      return true;
+      if(!cmDependsFortranStreamContainsSequence(finModFile, seq, seqlen))
+        {
+        // The module is of unexpected format.  Assume it is different.
+        std::cerr << compilerId << " fortran module " << modFile
+                  << " has unexpected format." << std::endl;
+        return true;
+        }
+
+      if(!cmDependsFortranStreamContainsSequence(finStampFile, seq, seqlen))
+        {
+        // The stamp must differ if the sequence is not contained.
+        return true;
+        }
       }
     }
   else if(strcmp(compilerId, "Intel") == 0)
diff --git a/Source/cmDocumentation.cxx b/Source/cmDocumentation.cxx
index 8d035af..3ff1017 100644
--- a/Source/cmDocumentation.cxx
+++ b/Source/cmDocumentation.cxx
@@ -113,7 +113,9 @@
   switch (ht)
     {
     case cmDocumentation::Usage:
-      return this->PrintDocumentationUsage(os);
+      return this->PrintUsage(os);
+    case cmDocumentation::Help:
+      return this->PrintHelp(os);
     case cmDocumentation::Full:
       return this->PrintHelpFull(os);
     case cmDocumentation::OneManual:
@@ -300,7 +302,7 @@
        (strcmp(argv[i], "-h") == 0) ||
        (strcmp(argv[i], "-H") == 0))
       {
-      help.HelpType = cmDocumentation::Usage;
+      help.HelpType = cmDocumentation::Help;
       GET_OPT_ARGUMENT(help.Argument);
       help.Argument = cmSystemTools::LowerCase(help.Argument);
       // special case for single command
@@ -841,7 +843,19 @@
 }
 
 //----------------------------------------------------------------------------
-bool cmDocumentation::PrintDocumentationUsage(std::ostream& os)
+bool cmDocumentation::PrintUsage(std::ostream& os)
+{
+  std::map<std::string,cmDocumentationSection*>::iterator si;
+  si = this->AllSections.find("Usage");
+  if(si != this->AllSections.end())
+    {
+    this->Formatter.PrintSection(os, *si->second);
+    }
+  return true;
+}
+
+//----------------------------------------------------------------------------
+bool cmDocumentation::PrintHelp(std::ostream& os)
 {
   std::map<std::string,cmDocumentationSection*>::iterator si;
   si = this->AllSections.find("Usage");
diff --git a/Source/cmDocumentation.h b/Source/cmDocumentation.h
index c98e48e..b72b5fe 100644
--- a/Source/cmDocumentation.h
+++ b/Source/cmDocumentation.h
@@ -102,6 +102,8 @@
   bool PrintFiles(std::ostream& os, std::string const& pattern);
 
   bool PrintVersion(std::ostream& os);
+  bool PrintUsage(std::ostream& os);
+  bool PrintHelp(std::ostream& os);
   bool PrintHelpFull(std::ostream& os);
   bool PrintHelpOneManual(std::ostream& os);
   bool PrintHelpOneCommand(std::ostream& os);
@@ -115,7 +117,6 @@
   bool PrintHelpListProperties(std::ostream& os);
   bool PrintHelpListVariables(std::ostream& os);
   bool PrintHelpListPolicies(std::ostream& os);
-  bool PrintDocumentationUsage(std::ostream& os);
   bool PrintOldCustomModules(std::ostream& os);
 
   const char* GetNameString() const;
diff --git a/Source/cmDocumentationFormatter.h b/Source/cmDocumentationFormatter.h
index 61766b9..59513cc 100644
--- a/Source/cmDocumentationFormatter.h
+++ b/Source/cmDocumentationFormatter.h
@@ -26,7 +26,7 @@
   /** Types of help provided.  */
   enum Type
   {
-    None, Version, Usage, Full, ListManuals,
+    None, Version, Usage, Help, Full, ListManuals,
     ListCommands, ListModules, ListProperties, ListVariables, ListPolicies,
     OneManual, OneCommand, OneModule, OneProperty, OneVariable, OnePolicy,
     OldCustomModules
diff --git a/Source/cmExpandedCommandArgument.cxx b/Source/cmExpandedCommandArgument.cxx
new file mode 100644
index 0000000..4477cf5
--- /dev/null
+++ b/Source/cmExpandedCommandArgument.cxx
@@ -0,0 +1,51 @@
+/*============================================================================
+  CMake - Cross Platform Makefile Generator
+  Copyright 2014 Kitware, Inc., Insight Software Consortium
+
+  Distributed under the OSI-approved BSD License (the "License");
+  see accompanying file Copyright.txt for details.
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the License for more information.
+============================================================================*/
+
+#include "cmExpandedCommandArgument.h"
+
+cmExpandedCommandArgument::cmExpandedCommandArgument():
+  Quoted(false)
+{
+
+}
+
+cmExpandedCommandArgument::cmExpandedCommandArgument(
+  std::string const& value, bool quoted):
+    Value(value), Quoted(quoted)
+{
+
+}
+
+std::string const& cmExpandedCommandArgument::GetValue() const
+{
+  return this->Value;
+}
+
+bool cmExpandedCommandArgument::WasQuoted() const
+{
+  return this->Quoted;
+}
+
+bool cmExpandedCommandArgument::operator== (std::string const& value) const
+{
+  return this->Value == value;
+}
+
+bool cmExpandedCommandArgument::empty() const
+{
+  return this->Value.empty();
+}
+
+const char* cmExpandedCommandArgument::c_str() const
+{
+  return this->Value.c_str();
+}
diff --git a/Source/cmExpandedCommandArgument.h b/Source/cmExpandedCommandArgument.h
new file mode 100644
index 0000000..f4e1517
--- /dev/null
+++ b/Source/cmExpandedCommandArgument.h
@@ -0,0 +1,45 @@
+/*============================================================================
+  CMake - Cross Platform Makefile Generator
+  Copyright 2014 Kitware, Inc., Insight Software Consortium
+
+  Distributed under the OSI-approved BSD License (the "License");
+  see accompanying file Copyright.txt for details.
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the License for more information.
+============================================================================*/
+#ifndef cmExpandedCommandArgument_h
+#define cmExpandedCommandArgument_h
+
+#include "cmStandardIncludes.h"
+
+/** \class cmExpandedCommandArgument
+ * \brief Represents an expanded command argument
+ *
+ * cmCommandArgument stores a string representing an expanded
+ * command argument and context information.
+ */
+
+class cmExpandedCommandArgument
+{
+public:
+  cmExpandedCommandArgument();
+  cmExpandedCommandArgument(std::string const& value, bool quoted);
+
+  std::string const& GetValue() const;
+
+  bool WasQuoted() const;
+
+  bool operator== (std::string const& value) const;
+
+  bool empty() const;
+
+  const char* c_str() const;
+
+private:
+  std::string Value;
+  bool Quoted;
+};
+
+#endif
diff --git a/Source/cmExportFileGenerator.cxx b/Source/cmExportFileGenerator.cxx
index 9f5eee5..1f39d7a 100644
--- a/Source/cmExportFileGenerator.cxx
+++ b/Source/cmExportFileGenerator.cxx
@@ -865,15 +865,16 @@
 }
 
 //----------------------------------------------------------------------------
+template <typename T>
 void
 cmExportFileGenerator
 ::SetImportLinkProperty(std::string const& suffix,
                         cmTarget* target,
                         const std::string& propName,
-                        std::vector<std::string> const& entries,
+                        std::vector<T> const& entries,
                         ImportPropertyMap& properties,
                         std::vector<std::string>& missingTargets
-                       )
+  )
 {
   // Skip the property if there are no entries.
   if(entries.empty())
@@ -884,7 +885,7 @@
   // Construct the property value.
   std::string link_entries;
   const char* sep = "";
-  for(std::vector<std::string>::const_iterator li = entries.begin();
+  for(typename std::vector<T>::const_iterator li = entries.begin();
       li != entries.end(); ++li)
     {
     // Separate this from the previous entry.
@@ -902,7 +903,6 @@
   properties[prop] = link_entries;
 }
 
-
 //----------------------------------------------------------------------------
 void cmExportFileGenerator::GenerateImportHeaderCode(std::ostream& os,
                                                     const std::string& config)
diff --git a/Source/cmExportFileGenerator.h b/Source/cmExportFileGenerator.h
index abd8ad5..919924e 100644
--- a/Source/cmExportFileGenerator.h
+++ b/Source/cmExportFileGenerator.h
@@ -95,9 +95,11 @@
                                  std::string const& suffix, cmTarget* target,
                                  ImportPropertyMap& properties,
                                  std::vector<std::string>& missingTargets);
+
+  template <typename T>
   void SetImportLinkProperty(std::string const& suffix,
                              cmTarget* target, const std::string& propName,
-                             std::vector<std::string> const& entries,
+                             std::vector<T> const& entries,
                              ImportPropertyMap& properties,
                              std::vector<std::string>& missingTargets);
 
diff --git a/Source/cmExportLibraryDependenciesCommand.cxx b/Source/cmExportLibraryDependenciesCommand.cxx
index 688d2eb..cb150a7 100644
--- a/Source/cmExportLibraryDependenciesCommand.cxx
+++ b/Source/cmExportLibraryDependenciesCommand.cxx
@@ -108,14 +108,12 @@
       std::string targetEntry = target.GetName();
       targetEntry += "_LIB_DEPENDS";
 
-      // Construct the dependency variable value.  It is safe to use
-      // the target GetLinkLibraries method here because this code is
-      // called at the end of configure but before generate so library
-      // dependencies have yet to be analyzed.  Therefore the value
-      // will be the direct link dependencies.
+      // Construct the dependency variable value with the direct link
+      // dependencies.
       std::string valueOld;
       std::string valueNew;
-      cmTarget::LinkLibraryVectorType const& libs = target.GetLinkLibraries();
+      cmTarget::LinkLibraryVectorType const& libs =
+        target.GetOriginalLinkLibraries();
       for(cmTarget::LinkLibraryVectorType::const_iterator li = libs.begin();
           li != libs.end(); ++li)
         {
diff --git a/Source/cmExtraCodeBlocksGenerator.cxx b/Source/cmExtraCodeBlocksGenerator.cxx
index 6f76dc4..56a6edb 100644
--- a/Source/cmExtraCodeBlocksGenerator.cxx
+++ b/Source/cmExtraCodeBlocksGenerator.cxx
@@ -574,7 +574,7 @@
         }
       }
 
-    const char* buildType = makefile->GetDefinition("CMAKE_BUILD_TYPE");
+    std::string buildType = makefile->GetSafeDefinition("CMAKE_BUILD_TYPE");
     std::string location;
     if ( target->GetType()==cmTarget::OBJECT_LIBRARY)
       {
diff --git a/Source/cmExtraEclipseCDT4Generator.cxx b/Source/cmExtraEclipseCDT4Generator.cxx
index e23551e..1beb3fd 100644
--- a/Source/cmExtraEclipseCDT4Generator.cxx
+++ b/Source/cmExtraEclipseCDT4Generator.cxx
@@ -968,7 +968,7 @@
         continue;
         }
       std::vector<std::string> includeDirs;
-      const char *config = mf->GetDefinition("CMAKE_BUILD_TYPE");
+      std::string config = mf->GetSafeDefinition("CMAKE_BUILD_TYPE");
       (*it)->GetIncludeDirectories(includeDirs, l->second, "C", config);
       this->AppendIncludeDirectories(fout, includeDirs, emmited);
       }
diff --git a/Source/cmFileCommand.cxx b/Source/cmFileCommand.cxx
index 655f3ba..1325cec 100644
--- a/Source/cmFileCommand.cxx
+++ b/Source/cmFileCommand.cxx
@@ -428,7 +428,8 @@
          arg_length_minimum,
          arg_length_maximum,
          arg__maximum,
-         arg_regex };
+         arg_regex,
+         arg_encoding };
   unsigned int minlen = 0;
   unsigned int maxlen = 0;
   int limit_input = -1;
@@ -438,6 +439,7 @@
   bool have_regex = false;
   bool newline_consume = false;
   bool hex_conversion_enabled = true;
+  bool utf8_encoding = false;
   int arg_mode = arg_none;
   for(unsigned int i=3; i < args.size(); ++i)
     {
@@ -475,6 +477,10 @@
       hex_conversion_enabled = false;
       arg_mode = arg_none;
       }
+    else if(args[i] == "ENCODING")
+      {
+      arg_mode = arg_encoding;
+      }
     else if(arg_mode == arg_limit_input)
       {
       if(sscanf(args[i].c_str(), "%d", &limit_input) != 1 ||
@@ -556,6 +562,22 @@
       have_regex = true;
       arg_mode = arg_none;
       }
+    else if(arg_mode == arg_encoding)
+      {
+      if(args[i] == "UTF-8")
+        {
+        utf8_encoding = true;
+        }
+      else
+        {
+        cmOStringStream e;
+        e << "STRINGS option ENCODING \""
+          << args[i] << "\" not recognized.";
+        this->SetError(e.str());
+        return false;
+        }
+      arg_mode = arg_none;
+      }
     else
       {
       cmOStringStream e;
@@ -596,11 +618,75 @@
   int output_size = 0;
   std::vector<std::string> strings;
   std::string s;
-  int c;
   while((!limit_count || strings.size() < limit_count) &&
         (limit_input < 0 || static_cast<int>(fin.tellg()) < limit_input) &&
-        (c = fin.get(), fin))
+        fin)
     {
+    std::string current_str;
+
+    int c = fin.get();
+
+    if(c == '\r')
+      {
+      // Ignore CR character to make output always have UNIX newlines.
+      continue;
+      }
+
+    else if((c >= 0x20 && c < 0x7F) || c == '\t' ||
+            (c == '\n' && newline_consume))
+      {
+      // This is an ASCII character that may be part of a string.
+      // Cast added to avoid compiler warning. Cast is ok because
+      // c is guaranteed to fit in char by the above if...
+      current_str += static_cast<char>(c);
+      }
+    else if(utf8_encoding)
+      {
+      // Check for UTF-8 encoded string (up to 4 octets)
+      static const unsigned char utf8_check_table[3][2] =
+        {
+          {0xE0, 0xC0},
+          {0xF0, 0xE0},
+          {0xF8, 0xF0},
+        };
+
+      // how many octets are there?
+      unsigned int num_utf8_bytes = 0;
+      for(unsigned int j=0; num_utf8_bytes == 0 && j<3; j++)
+        {
+        if((c & utf8_check_table[j][0]) == utf8_check_table[j][1])
+          num_utf8_bytes = j+2;
+        }
+
+      // get subsequent octets and check that they are valid
+      for(unsigned int j=0; j<num_utf8_bytes; j++)
+        {
+        if(j != 0)
+          {
+          c = fin.get();
+          if(!fin || (c & 0xC0) != 0x80)
+            {
+            fin.putback(static_cast<char>(c));
+            break;
+            }
+          }
+        current_str += static_cast<char>(c);
+        }
+
+      // if this was an invalid utf8 sequence, discard the data, and put
+      // back subsequent characters
+      if((current_str.length() != num_utf8_bytes))
+        {
+        for(unsigned int j=0; j<current_str.size()-1; j++)
+          {
+          c = current_str[current_str.size() - 1 - j];
+          fin.putback(static_cast<char>(c));
+          }
+        current_str = "";
+        }
+      }
+
+
     if(c == '\n' && !newline_consume)
       {
       // The current line has been terminated.  Check if the current
@@ -621,26 +707,13 @@
       // Reset the string to empty.
       s = "";
       }
-    else if(c == '\r')
+    else if(current_str.empty())
       {
-      // Ignore CR character to make output always have UNIX newlines.
-      }
-    else if((c >= 0x20 && c < 0x7F) || c == '\t' ||
-            (c == '\n' && newline_consume))
-      {
-      // This is an ASCII character that may be part of a string.
-      // Cast added to avoid compiler warning. Cast is ok because
-      // c is guaranteed to fit in char by the above if...
-      s += static_cast<char>(c);
-      }
-    else
-      {
-      // TODO: Support ENCODING option.  See issue #10519.
       // A non-string character has been found.  Check if the current
       // string matches the requirements.  We require that the length
       // be at least one no matter what the user specified.
       if(s.length() >= minlen && s.length() >= 1 &&
-         (!have_regex || regex.find(s.c_str())))
+      (!have_regex || regex.find(s.c_str())))
         {
         output_size += static_cast<int>(s.size()) + 1;
         if(limit_output >= 0 && output_size >= limit_output)
@@ -654,10 +727,15 @@
       // Reset the string to empty.
       s = "";
       }
+    else
+      {
+      s += current_str;
+      }
 
-    // Terminate a string if the maximum length is reached.
+
     if(maxlen > 0 && s.size() == maxlen)
       {
+      // Terminate a string if the maximum length is reached.
       if(s.length() >= minlen &&
          (!have_regex || regex.find(s.c_str())))
         {
@@ -1613,7 +1691,8 @@
                                     MatchProperties const& match_properties)
 {
   // Inform the user about this directory installation.
-  this->ReportCopy(destination, TypeDir, true);
+  this->ReportCopy(destination, TypeDir,
+                   !cmSystemTools::FileIsDirectory(destination));
 
   // Make sure the destination directory exists.
   if(!cmSystemTools::MakeDirectory(destination))
@@ -1704,6 +1783,9 @@
     cmFileCopier(command, "INSTALL"),
     InstallType(cmInstallType_FILES),
     Optional(false),
+    MessageAlways(false),
+    MessageLazy(false),
+    MessageNever(false),
     DestDirLength(0)
     {
     // Installation does not use source permissions by default.
@@ -1725,6 +1807,9 @@
 protected:
   cmInstallType InstallType;
   bool Optional;
+  bool MessageAlways;
+  bool MessageLazy;
+  bool MessageNever;
   int DestDirLength;
   std::string Rename;
 
@@ -1740,9 +1825,12 @@
 
   virtual void ReportCopy(const char* toFile, Type type, bool copy)
     {
-    std::string message = (copy? "Installing: " : "Up-to-date: ");
-    message += toFile;
-    this->Makefile->DisplayStatus(message.c_str(), -1);
+    if(!this->MessageNever && (copy || !this->MessageLazy))
+      {
+      std::string message = (copy? "Installing: " : "Up-to-date: ");
+      message += toFile;
+      this->Makefile->DisplayStatus(message.c_str(), -1);
+      }
     if(type != TypeDir)
       {
       // Add the file to the manifest.
@@ -1828,6 +1916,16 @@
     return false;
     }
 
+  if(((this->MessageAlways?1:0) +
+      (this->MessageLazy?1:0) +
+      (this->MessageNever?1:0)) > 1)
+    {
+    this->FileCommand->SetError("INSTALL options MESSAGE_ALWAYS, "
+                                "MESSAGE_LAZY, and MESSAGE_NEVER "
+                                "are mutually exclusive.");
+    return false;
+    }
+
   return true;
 }
 
@@ -1879,6 +1977,42 @@
       this->Optional = true;
       }
     }
+  else if(arg == "MESSAGE_ALWAYS")
+    {
+    if(this->CurrentMatchRule)
+      {
+      this->NotAfterMatch(arg);
+      }
+    else
+      {
+      this->Doing = DoingNone;
+      this->MessageAlways = true;
+      }
+    }
+  else if(arg == "MESSAGE_LAZY")
+    {
+    if(this->CurrentMatchRule)
+      {
+      this->NotAfterMatch(arg);
+      }
+    else
+      {
+      this->Doing = DoingNone;
+      this->MessageLazy = true;
+      }
+    }
+  else if(arg == "MESSAGE_NEVER")
+    {
+    if(this->CurrentMatchRule)
+      {
+      this->NotAfterMatch(arg);
+      }
+    else
+      {
+      this->Doing = DoingNone;
+      this->MessageNever = true;
+      }
+    }
   else if(arg == "PERMISSIONS")
     {
     if(this->CurrentMatchRule)
@@ -2057,23 +2191,26 @@
     this->DestDirLength = int(sdestdir.size());
     }
 
-  if ( !cmSystemTools::FileExists(destination.c_str()) )
+  if(this->InstallType != cmInstallType_DIRECTORY)
     {
-    if ( !cmSystemTools::MakeDirectory(destination.c_str()) )
+    if ( !cmSystemTools::FileExists(destination.c_str()) )
       {
-      std::string errstring = "cannot create directory: " + destination +
+      if ( !cmSystemTools::MakeDirectory(destination.c_str()) )
+        {
+        std::string errstring = "cannot create directory: " + destination +
           ". Maybe need administrative privileges.";
+        this->FileCommand->SetError(errstring);
+        return false;
+        }
+      }
+    if ( !cmSystemTools::FileIsDirectory(destination.c_str()) )
+      {
+      std::string errstring = "INSTALL destination: " + destination +
+        " is not a directory.";
       this->FileCommand->SetError(errstring);
       return false;
       }
     }
-  if ( !cmSystemTools::FileIsDirectory(destination.c_str()) )
-    {
-    std::string errstring = "INSTALL destination: " + destination +
-        " is not a directory.";
-    this->FileCommand->SetError(errstring);
-    return false;
-    }
   return true;
 }
 
@@ -3113,15 +3250,7 @@
     return false;
     }
 
-  struct stat st;
-  if(::stat(filename.c_str(), &st))
-    {
-    std::string errStr = "UPLOAD cannot stat file '";
-    errStr += filename + "'.";
-    this->SetError(errStr);
-    fclose(fin);
-    return false;
-    }
+  unsigned long file_size = cmsys::SystemTools::FileLength(filename.c_str());
 
   ::CURL *curl;
   ::curl_global_init(CURL_GLOBAL_DEFAULT);
@@ -3211,7 +3340,7 @@
 
   // and give the size of the upload (optional)
   res = ::curl_easy_setopt(curl,
-    CURLOPT_INFILESIZE, static_cast<long>(st.st_size));
+    CURLOPT_INFILESIZE, static_cast<long>(file_size));
   check_curl_result(res, "UPLOAD cannot set input file size: ");
 
   res = ::curl_easy_perform(curl);
diff --git a/Source/cmGeneratorExpression.cxx b/Source/cmGeneratorExpression.cxx
index 028d229..7fc1464 100644
--- a/Source/cmGeneratorExpression.cxx
+++ b/Source/cmGeneratorExpression.cxx
@@ -97,6 +97,7 @@
   context.Quiet = quiet;
   context.HadError = false;
   context.HadContextSensitiveCondition = false;
+  context.HadHeadSensitiveCondition = false;
   context.HeadTarget = headTarget;
   context.EvaluateForBuildsystem = this->EvaluateForBuildsystem;
   context.CurrentTarget = currentTarget ? currentTarget : headTarget;
@@ -124,6 +125,7 @@
   if (!context.HadError)
     {
     this->HadContextSensitiveCondition = context.HadContextSensitiveCondition;
+    this->HadHeadSensitiveCondition = context.HadHeadSensitiveCondition;
     }
 
   this->DependTargets = context.DependTargets;
@@ -137,6 +139,7 @@
               const std::string& input)
   : Backtrace(backtrace), Input(input),
     HadContextSensitiveCondition(false),
+    HadHeadSensitiveCondition(false),
     EvaluateForBuildsystem(false)
 {
   cmGeneratorExpressionLexer l;
@@ -469,12 +472,11 @@
 //----------------------------------------------------------------------------
 bool cmGeneratorExpression::IsValidTargetName(const std::string &input)
 {
-  cmsys::RegularExpression targetNameValidator;
   // The ':' is supported to allow use with IMPORTED targets. At least
   // Qt 4 and 5 IMPORTED targets use ':' as the namespace delimiter.
-  targetNameValidator.compile("^[A-Za-z0-9_.:+-]+$");
+  static cmsys::RegularExpression targetNameValidator("^[A-Za-z0-9_.:+-]+$");
 
-  return targetNameValidator.find(input.c_str());
+  return targetNameValidator.find(input);
 }
 
 //----------------------------------------------------------------------------
diff --git a/Source/cmGeneratorExpression.h b/Source/cmGeneratorExpression.h
index 324d23c..b952520 100644
--- a/Source/cmGeneratorExpression.h
+++ b/Source/cmGeneratorExpression.h
@@ -111,6 +111,10 @@
   {
     return this->HadContextSensitiveCondition;
   }
+  bool GetHadHeadSensitiveCondition() const
+  {
+    return this->HadHeadSensitiveCondition;
+  }
 
   void SetEvaluateForBuildsystem(bool eval)
   {
@@ -141,6 +145,7 @@
                                                           MaxLanguageStandard;
   mutable std::string Output;
   mutable bool HadContextSensitiveCondition;
+  mutable bool HadHeadSensitiveCondition;
   bool EvaluateForBuildsystem;
 };
 
diff --git a/Source/cmGeneratorExpressionEvaluator.cxx b/Source/cmGeneratorExpressionEvaluator.cxx
index c54922d..c1478df 100644
--- a/Source/cmGeneratorExpressionEvaluator.cxx
+++ b/Source/cmGeneratorExpressionEvaluator.cxx
@@ -394,16 +394,14 @@
                        cmGeneratorExpressionDAGChecker *,
                        const std::string &lang) const
   {
-    const char *compilerId = context->Makefile ?
-                              context->Makefile->GetSafeDefinition(
-                                      "CMAKE_" + lang + "_COMPILER_ID") : "";
+    const char *compilerId =
+      context->Makefile->GetSafeDefinition("CMAKE_" + lang + "_COMPILER_ID");
     if (parameters.size() == 0)
       {
       return compilerId ? compilerId : "";
       }
-    cmsys::RegularExpression compilerIdValidator;
-    compilerIdValidator.compile("^[A-Za-z0-9_]*$");
-    if (!compilerIdValidator.find(parameters.begin()->c_str()))
+    static cmsys::RegularExpression compilerIdValidator("^[A-Za-z0-9_]*$");
+    if (!compilerIdValidator.find(*parameters.begin()))
       {
       reportError(context, content->GetOriginalExpression(),
                   "Expression syntax not recognized.");
@@ -501,17 +499,15 @@
                        cmGeneratorExpressionDAGChecker *,
                        const std::string &lang) const
   {
-    const char *compilerVersion = context->Makefile ?
-                              context->Makefile->GetSafeDefinition(
-                                  "CMAKE_" + lang + "_COMPILER_VERSION") : "";
+    const char *compilerVersion = context->Makefile->GetSafeDefinition(
+        "CMAKE_" + lang + "_COMPILER_VERSION");
     if (parameters.size() == 0)
       {
       return compilerVersion ? compilerVersion : "";
       }
 
-    cmsys::RegularExpression compilerIdValidator;
-    compilerIdValidator.compile("^[0-9\\.]*$");
-    if (!compilerIdValidator.find(parameters.begin()->c_str()))
+    static cmsys::RegularExpression compilerIdValidator("^[0-9\\.]*$");
+    if (!compilerIdValidator.find(*parameters.begin()))
       {
       reportError(context, content->GetOriginalExpression(),
                   "Expression syntax not recognized.");
@@ -585,9 +581,8 @@
                        const GeneratorExpressionContent *,
                        cmGeneratorExpressionDAGChecker *) const
   {
-    const char *platformId = context->Makefile ?
-                              context->Makefile->GetSafeDefinition(
-                        "CMAKE_SYSTEM_NAME") : "";
+    const char *platformId =
+      context->Makefile->GetSafeDefinition("CMAKE_SYSTEM_NAME");
     if (parameters.size() == 0)
       {
       return platformId ? platformId : "";
@@ -711,9 +706,8 @@
       {
       return configurationNode.Evaluate(parameters, context, content, 0);
       }
-    cmsys::RegularExpression configValidator;
-    configValidator.compile("^[A-Za-z0-9_]*$");
-    if (!configValidator.find(parameters.begin()->c_str()))
+    static cmsys::RegularExpression configValidator("^[A-Za-z0-9_]*$");
+    if (!configValidator.find(*parameters.begin()))
       {
       reportError(context, content->GetOriginalExpression(),
                   "Expression syntax not recognized.");
@@ -802,68 +796,57 @@
 
 #undef TRANSITIVE_PROPERTY_NAME
 
-std::string getLinkedTargetsContent(const std::vector<cmTarget*> &targets,
-                                  cmTarget const* target,
-                                  cmTarget const* headTarget,
-                                  cmGeneratorExpressionContext *context,
-                                  cmGeneratorExpressionDAGChecker *dagChecker,
-                                  const std::string &interfacePropertyName)
+template <typename T>
+std::string
+getLinkedTargetsContent(
+  std::vector<T> const &libraries,
+  cmTarget const* target,
+  cmTarget const* headTarget,
+  cmGeneratorExpressionContext *context,
+  cmGeneratorExpressionDAGChecker *dagChecker,
+  const std::string &interfacePropertyName)
 {
-  cmGeneratorExpression ge(&context->Backtrace);
-
+  std::string linkedTargetsContent;
   std::string sep;
   std::string depString;
-  for (std::vector<cmTarget*>::const_iterator
-      it = targets.begin();
-      it != targets.end(); ++it)
+  for (typename std::vector<T>::const_iterator it = libraries.begin();
+       it != libraries.end(); ++it)
     {
-    if (*it == target)
+    // Broken code can have a target in its own link interface.
+    // Don't follow such link interface entries so as not to create a
+    // self-referencing loop.
+    if (it->Target && it->Target != target)
       {
-      // Broken code can have a target in its own link interface.
-      // Don't follow such link interface entries so as not to create a
-      // self-referencing loop.
-      continue;
+      depString +=
+        sep + "$<TARGET_PROPERTY:" +
+        it->Target->GetName() + "," + interfacePropertyName + ">";
+      sep = ";";
       }
-    depString +=
-      sep + "$<TARGET_PROPERTY:" +
-        (*it)->GetName() + "," + interfacePropertyName + ">";
-    sep = ";";
     }
-  cmsys::auto_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(depString);
-  std::string linkedTargetsContent = cge->Evaluate(context->Makefile,
-                      context->Config,
-                      context->Quiet,
-                      headTarget,
-                      target,
-                      dagChecker);
-  if (cge->GetHadContextSensitiveCondition())
+  if(!depString.empty())
     {
-    context->HadContextSensitiveCondition = true;
+    cmGeneratorExpression ge(&context->Backtrace);
+    cmsys::auto_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(depString);
+    linkedTargetsContent = cge->Evaluate(target->GetMakefile(),
+                                         context->Config,
+                                         context->Quiet,
+                                         headTarget,
+                                         target,
+                                         dagChecker);
+    if (cge->GetHadContextSensitiveCondition())
+      {
+      context->HadContextSensitiveCondition = true;
+      }
+    if (cge->GetHadHeadSensitiveCondition())
+      {
+      context->HadHeadSensitiveCondition = true;
+      }
     }
+  linkedTargetsContent =
+    cmGeneratorExpression::StripEmptyListElements(linkedTargetsContent);
   return linkedTargetsContent;
 }
 
-std::string getLinkedTargetsContent(const std::vector<std::string> &libraries,
-                                  cmTarget const* target,
-                                  cmTarget const* headTarget,
-                                  cmGeneratorExpressionContext *context,
-                                  cmGeneratorExpressionDAGChecker *dagChecker,
-                                  const std::string &interfacePropertyName)
-{
-  std::vector<cmTarget*> tgts;
-  for (std::vector<std::string>::const_iterator
-      it = libraries.begin();
-      it != libraries.end(); ++it)
-    {
-    if (cmTarget *tgt = context->Makefile->FindTargetToUse(*it))
-      {
-      tgts.push_back(tgt);
-      }
-    }
-  return getLinkedTargetsContent(tgts, target, headTarget, context,
-                                 dagChecker, interfacePropertyName);
-}
-
 //----------------------------------------------------------------------------
 static const struct TargetPropertyNode : public cmGeneratorExpressionNode
 {
@@ -884,12 +867,15 @@
           "$<TARGET_PROPERTY:...> expression requires one or two parameters");
       return std::string();
       }
-    cmsys::RegularExpression propertyNameValidator;
-    propertyNameValidator.compile("^[A-Za-z0-9_]+$");
+    static cmsys::RegularExpression propertyNameValidator("^[A-Za-z0-9_]+$");
 
     cmTarget const* target = context->HeadTarget;
     std::string propertyName = *parameters.begin();
 
+    if (parameters.size() == 1)
+      {
+      context->HadHeadSensitiveCondition = true;
+      }
     if (!target && parameters.size() == 1)
       {
       reportError(context, content->GetOriginalExpression(),
@@ -973,7 +959,7 @@
       return std::string();
       }
 
-    if (!propertyNameValidator.find(propertyName.c_str()))
+    if (!propertyNameValidator.find(propertyName))
       {
       ::reportError(context, content->GetOriginalExpression(),
                     "Property name not supported.");
@@ -1031,6 +1017,19 @@
       {
       if (dagCheckerParent->EvaluatingLinkLibraries())
         {
+#define TRANSITIVE_PROPERTY_COMPARE(PROPERTY) \
+    (#PROPERTY == propertyName || "INTERFACE_" #PROPERTY == propertyName) ||
+        if (CM_FOR_EACH_TRANSITIVE_PROPERTY_NAME(TRANSITIVE_PROPERTY_COMPARE)
+            false)
+          {
+          reportError(context, content->GetOriginalExpression(),
+              "$<TARGET_PROPERTY:...> expression in link libraries "
+              "evaluation depends on target property which is transitive "
+              "over the link libraries, creating a recursion.");
+          return std::string();
+          }
+#undef TRANSITIVE_PROPERTY_COMPARE
+
         if(!prop)
           {
           return std::string();
@@ -1045,19 +1044,25 @@
           CM_FOR_EACH_TRANSITIVE_PROPERTY_METHOD(
                                             ASSERT_TRANSITIVE_PROPERTY_METHOD)
           false);
-        }
 #undef ASSERT_TRANSITIVE_PROPERTY_METHOD
+        }
       }
 
     std::string linkedTargetsContent;
 
     std::string interfacePropertyName;
+    bool isInterfaceProperty = false;
 
 #define POPULATE_INTERFACE_PROPERTY_NAME(prop) \
-    if (propertyName == #prop || propertyName == "INTERFACE_" #prop) \
+    if (propertyName == #prop) \
       { \
       interfacePropertyName = "INTERFACE_" #prop; \
       } \
+    else if (propertyName == "INTERFACE_" #prop) \
+      { \
+      interfacePropertyName = "INTERFACE_" #prop; \
+      isInterfaceProperty = true; \
+      } \
     else
 
     CM_FOR_EACH_TRANSITIVE_PROPERTY_NAME(POPULATE_INTERFACE_PROPERTY_NAME)
@@ -1073,50 +1078,34 @@
         }
       }
 #undef POPULATE_INTERFACE_PROPERTY_NAME
-
-    cmTarget const* headTarget = context->HeadTarget
+    cmTarget const* headTarget = context->HeadTarget && isInterfaceProperty
                                ? context->HeadTarget : target;
 
-    const char * const *transBegin =
-                        cmArrayBegin(targetPropertyTransitiveWhitelist) + 1;
-    const char * const *transEnd =
-                        cmArrayEnd(targetPropertyTransitiveWhitelist);
-
-    if (std::find_if(transBegin, transEnd,
-                     cmStrCmp(propertyName)) != transEnd)
+    if(isInterfaceProperty)
       {
-
-      std::vector<cmTarget*> tgts;
-      target->GetTransitivePropertyTargets(context->Config,
-                                                 headTarget, tgts);
-      if (!tgts.empty())
+      if(cmTarget::LinkInterfaceLibraries const* iface =
+         target->GetLinkInterfaceLibraries(context->Config, headTarget, true))
         {
         linkedTargetsContent =
-                  getLinkedTargetsContent(tgts, target,
-                                          headTarget,
-                                          context, &dagChecker,
-                                          interfacePropertyName);
+          getLinkedTargetsContent(iface->Libraries, target,
+                                  headTarget,
+                                  context, &dagChecker,
+                                  interfacePropertyName);
         }
       }
-    else if (std::find_if(transBegin, transEnd,
-                          cmStrCmp(interfacePropertyName)) != transEnd)
+    else if(!interfacePropertyName.empty())
       {
-      const cmTarget::LinkImplementation *impl
-          = target->GetLinkImplementationLibraries(context->Config,
-                                                   headTarget);
-      if(impl)
+      if(cmTarget::LinkImplementationLibraries const* impl =
+         target->GetLinkImplementationLibraries(context->Config))
         {
         linkedTargetsContent =
-                  getLinkedTargetsContent(impl->Libraries, target,
-                                          headTarget,
-                                          context, &dagChecker,
-                                          interfacePropertyName);
+          getLinkedTargetsContent(impl->Libraries, target,
+                                  target,
+                                  context, &dagChecker,
+                                  interfacePropertyName);
         }
       }
 
-    linkedTargetsContent =
-          cmGeneratorExpression::StripEmptyListElements(linkedTargetsContent);
-
     if (!prop)
       {
       if (target->IsImported()
@@ -1190,31 +1179,31 @@
         return propContent ? propContent : "";
         }
       }
-    for (size_t i = 1;
-         i < cmArraySize(targetPropertyTransitiveWhitelist);
-         ++i)
+    if(!interfacePropertyName.empty())
       {
-      if (targetPropertyTransitiveWhitelist[i] == interfacePropertyName)
-        {
-        cmGeneratorExpression ge(&context->Backtrace);
-        cmsys::auto_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(prop);
-        std::string result = cge->Evaluate(context->Makefile,
+      cmGeneratorExpression ge(&context->Backtrace);
+      cmsys::auto_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(prop);
+      cge->SetEvaluateForBuildsystem(context->EvaluateForBuildsystem);
+      std::string result = cge->Evaluate(context->Makefile,
                             context->Config,
                             context->Quiet,
                             headTarget,
                             target,
                             &dagChecker);
 
-        if (cge->GetHadContextSensitiveCondition())
-          {
-          context->HadContextSensitiveCondition = true;
-          }
-        if (!linkedTargetsContent.empty())
-          {
-          result += (result.empty() ? "" : ";") + linkedTargetsContent;
-          }
-        return result;
+      if (cge->GetHadContextSensitiveCondition())
+        {
+        context->HadContextSensitiveCondition = true;
         }
+      if (cge->GetHadHeadSensitiveCondition())
+        {
+        context->HadHeadSensitiveCondition = true;
+        }
+      if (!linkedTargetsContent.empty())
+        {
+        result += (result.empty() ? "" : ";") + linkedTargetsContent;
+        }
+      return result;
       }
     return prop;
   }
@@ -1333,6 +1322,7 @@
           "not be used with add_custom_command or add_custom_target.");
       return std::string();
       }
+    context->HadHeadSensitiveCondition = true;
 
     typedef std::map<std::string, std::vector<std::string> > LangMap;
     static LangMap availableFeatures;
@@ -1466,6 +1456,7 @@
       }
 
     context->HadContextSensitiveCondition = true;
+    context->HadHeadSensitiveCondition = true;
 
     for (size_t i = 1; i < cmArraySize(targetPolicyWhitelist); ++i)
       {
@@ -1529,7 +1520,17 @@
 } installPrefixNode;
 
 //----------------------------------------------------------------------------
-template<bool linker, bool soname>
+class ArtifactNameTag;
+class ArtifactLinkerTag;
+class ArtifactSonameTag;
+class ArtifactPdbTag;
+
+class ArtifactPathTag;
+class ArtifactDirTag;
+class ArtifactNameTag;
+
+//----------------------------------------------------------------------------
+template<typename ArtifactT>
 struct TargetFilesystemArtifactResultCreator
 {
   static std::string Create(cmTarget* target,
@@ -1539,7 +1540,7 @@
 
 //----------------------------------------------------------------------------
 template<>
-struct TargetFilesystemArtifactResultCreator<false, true>
+struct TargetFilesystemArtifactResultCreator<ArtifactSonameTag>
 {
   static std::string Create(cmTarget* target,
                             cmGeneratorExpressionContext *context,
@@ -1569,7 +1570,45 @@
 
 //----------------------------------------------------------------------------
 template<>
-struct TargetFilesystemArtifactResultCreator<true, false>
+struct TargetFilesystemArtifactResultCreator<ArtifactPdbTag>
+{
+  static std::string Create(cmTarget* target,
+                            cmGeneratorExpressionContext *context,
+                            const GeneratorExpressionContent *content)
+  {
+    std::string language = target->GetLinkerLanguage(context->Config);
+
+    std::string pdbSupportVar = "CMAKE_" + language + "_LINKER_SUPPORTS_PDB";
+
+    if(!context->Makefile->IsOn(pdbSupportVar))
+      {
+      ::reportError(context, content->GetOriginalExpression(),
+                    "TARGET_PDB_FILE is not supported by the target linker.");
+      return std::string();
+      }
+
+    cmTarget::TargetType targetType = target->GetType();
+
+    if(targetType != cmTarget::SHARED_LIBRARY &&
+       targetType != cmTarget::MODULE_LIBRARY &&
+       targetType != cmTarget::EXECUTABLE)
+      {
+      ::reportError(context, content->GetOriginalExpression(),
+                    "TARGET_PDB_FILE is allowed only for "
+                    "targets with linker created artifacts.");
+      return std::string();
+      }
+
+    std::string result = target->GetPDBDirectory(context->Config);
+    result += "/";
+    result += target->GetPDBName(context->Config);
+    return result;
+  }
+};
+
+//----------------------------------------------------------------------------
+template<>
+struct TargetFilesystemArtifactResultCreator<ArtifactLinkerTag>
 {
   static std::string Create(cmTarget* target,
                             cmGeneratorExpressionContext *context,
@@ -1590,7 +1629,7 @@
 
 //----------------------------------------------------------------------------
 template<>
-struct TargetFilesystemArtifactResultCreator<false, false>
+struct TargetFilesystemArtifactResultCreator<ArtifactNameTag>
 {
   static std::string Create(cmTarget* target,
                             cmGeneratorExpressionContext *context,
@@ -1602,7 +1641,7 @@
 
 
 //----------------------------------------------------------------------------
-template<bool dirQual, bool nameQual>
+template<typename ArtifactT>
 struct TargetFilesystemArtifactResultGetter
 {
   static std::string Get(const std::string &result);
@@ -1610,7 +1649,7 @@
 
 //----------------------------------------------------------------------------
 template<>
-struct TargetFilesystemArtifactResultGetter<false, true>
+struct TargetFilesystemArtifactResultGetter<ArtifactNameTag>
 {
   static std::string Get(const std::string &result)
   { return cmSystemTools::GetFilenameName(result); }
@@ -1618,7 +1657,7 @@
 
 //----------------------------------------------------------------------------
 template<>
-struct TargetFilesystemArtifactResultGetter<true, false>
+struct TargetFilesystemArtifactResultGetter<ArtifactDirTag>
 {
   static std::string Get(const std::string &result)
   { return cmSystemTools::GetFilenamePath(result); }
@@ -1626,14 +1665,14 @@
 
 //----------------------------------------------------------------------------
 template<>
-struct TargetFilesystemArtifactResultGetter<false, false>
+struct TargetFilesystemArtifactResultGetter<ArtifactPathTag>
 {
   static std::string Get(const std::string &result)
   { return result; }
 };
 
 //----------------------------------------------------------------------------
-template<bool linker, bool soname, bool dirQual, bool nameQual>
+template<typename ArtifactT, typename ComponentT>
 struct TargetFilesystemArtifact : public cmGeneratorExpressionNode
 {
   TargetFilesystemArtifact() {}
@@ -1681,7 +1720,7 @@
     context->AllTargets.insert(target);
 
     std::string result =
-                TargetFilesystemArtifactResultCreator<linker, soname>::Create(
+                TargetFilesystemArtifactResultCreator<ArtifactT>::Create(
                           target,
                           context,
                           content);
@@ -1690,29 +1729,35 @@
       return std::string();
       }
     return
-        TargetFilesystemArtifactResultGetter<dirQual, nameQual>::Get(result);
+        TargetFilesystemArtifactResultGetter<ComponentT>::Get(result);
   }
 };
 
 //----------------------------------------------------------------------------
+template<typename ArtifactT>
+struct TargetFilesystemArtifactNodeGroup
+{
+  TargetFilesystemArtifactNodeGroup()
+    {
+    }
+
+  TargetFilesystemArtifact<ArtifactT, ArtifactPathTag> File;
+  TargetFilesystemArtifact<ArtifactT, ArtifactNameTag> FileName;
+  TargetFilesystemArtifact<ArtifactT, ArtifactDirTag> FileDir;
+};
+
+//----------------------------------------------------------------------------
 static const
-TargetFilesystemArtifact<false, false, false, false> targetFileNode;
+TargetFilesystemArtifactNodeGroup<ArtifactNameTag> targetNodeGroup;
+
 static const
-TargetFilesystemArtifact<true, false, false, false> targetLinkerFileNode;
+TargetFilesystemArtifactNodeGroup<ArtifactLinkerTag> targetLinkerNodeGroup;
+
 static const
-TargetFilesystemArtifact<false, true, false, false> targetSoNameFileNode;
+TargetFilesystemArtifactNodeGroup<ArtifactSonameTag> targetSoNameNodeGroup;
+
 static const
-TargetFilesystemArtifact<false, false, false, true> targetFileNameNode;
-static const
-TargetFilesystemArtifact<true, false, false, true> targetLinkerFileNameNode;
-static const
-TargetFilesystemArtifact<false, true, false, true> targetSoNameFileNameNode;
-static const
-TargetFilesystemArtifact<false, false, true, false> targetFileDirNode;
-static const
-TargetFilesystemArtifact<true, false, true, false> targetLinkerFileDirNode;
-static const
-TargetFilesystemArtifact<false, true, true, false> targetSoNameFileDirNode;
+TargetFilesystemArtifactNodeGroup<ArtifactPdbTag> targetPdbNodeGroup;
 
 //----------------------------------------------------------------------------
 static const
@@ -1738,15 +1783,18 @@
     nodeMap["COMPILE_FEATURES"] = &compileFeaturesNode;
     nodeMap["CONFIGURATION"] = &configurationNode;
     nodeMap["CONFIG"] = &configurationTestNode;
-    nodeMap["TARGET_FILE"] = &targetFileNode;
-    nodeMap["TARGET_LINKER_FILE"] = &targetLinkerFileNode;
-    nodeMap["TARGET_SONAME_FILE"] = &targetSoNameFileNode;
-    nodeMap["TARGET_FILE_NAME"] = &targetFileNameNode;
-    nodeMap["TARGET_LINKER_FILE_NAME"] = &targetLinkerFileNameNode;
-    nodeMap["TARGET_SONAME_FILE_NAME"] = &targetSoNameFileNameNode;
-    nodeMap["TARGET_FILE_DIR"] = &targetFileDirNode;
-    nodeMap["TARGET_LINKER_FILE_DIR"] = &targetLinkerFileDirNode;
-    nodeMap["TARGET_SONAME_FILE_DIR"] = &targetSoNameFileDirNode;
+    nodeMap["TARGET_FILE"] = &targetNodeGroup.File;
+    nodeMap["TARGET_LINKER_FILE"] = &targetLinkerNodeGroup.File;
+    nodeMap["TARGET_SONAME_FILE"] = &targetSoNameNodeGroup.File;
+    nodeMap["TARGET_PDB_FILE"] = &targetPdbNodeGroup.File;
+    nodeMap["TARGET_FILE_NAME"] = &targetNodeGroup.FileName;
+    nodeMap["TARGET_LINKER_FILE_NAME"] = &targetLinkerNodeGroup.FileName;
+    nodeMap["TARGET_SONAME_FILE_NAME"] = &targetSoNameNodeGroup.FileName;
+    nodeMap["TARGET_PDB_FILE_NAME"] = &targetPdbNodeGroup.FileName;
+    nodeMap["TARGET_FILE_DIR"] = &targetNodeGroup.FileDir;
+    nodeMap["TARGET_LINKER_FILE_DIR"] = &targetLinkerNodeGroup.FileDir;
+    nodeMap["TARGET_SONAME_FILE_DIR"] = &targetSoNameNodeGroup.FileDir;
+    nodeMap["TARGET_PDB_FILE_DIR"] = &targetPdbNodeGroup.FileDir;
     nodeMap["STREQUAL"] = &strEqualNode;
     nodeMap["EQUAL"] = &equalNode;
     nodeMap["LOWER_CASE"] = &lowerCaseNode;
diff --git a/Source/cmGeneratorExpressionEvaluator.h b/Source/cmGeneratorExpressionEvaluator.h
index 0ffb860..8a529e8 100644
--- a/Source/cmGeneratorExpressionEvaluator.h
+++ b/Source/cmGeneratorExpressionEvaluator.h
@@ -41,6 +41,7 @@
   bool Quiet;
   bool HadError;
   bool HadContextSensitiveCondition;
+  bool HadHeadSensitiveCondition;
   bool EvaluateForBuildsystem;
 };
 
diff --git a/Source/cmGeneratorTarget.cxx b/Source/cmGeneratorTarget.cxx
index a7576ed..14b5a92 100644
--- a/Source/cmGeneratorTarget.cxx
+++ b/Source/cmGeneratorTarget.cxx
@@ -38,7 +38,8 @@
       {
       e << "  " << (*i)->GetLocation().GetName() << "\n";
       }
-    e << "but may contain only headers and sources that compile.";
+    e << "but may contain only sources that compile, header files, and "
+         "other files that would not affect linking of a normal library.";
     cm->IssueMessage(cmake::FATAL_ERROR, e.str(),
                      target->GetBacktrace());
     }
@@ -52,6 +53,8 @@
 struct IDLSourcesTag {};
 struct ResxTag {};
 struct ModuleDefinitionFileTag {};
+struct AppManifestTag{};
+struct CertificatesTag{};
 
 #if !defined(_MSC_VER) || _MSC_VER >= 1310
 template<typename Tag, typename OtherTag>
@@ -194,6 +197,14 @@
       {
       DoAccept<IsSameTag<Tag, ResxTag>::Result>::Do(this->Data, sf);
       }
+    else if (ext == "appxmanifest")
+      {
+      DoAccept<IsSameTag<Tag, AppManifestTag>::Result>::Do(this->Data, sf);
+      }
+    else if (ext == "pfx")
+      {
+      DoAccept<IsSameTag<Tag, CertificatesTag>::Result>::Do(this->Data, sf);
+      }
     else if(this->Header.find(sf->GetFullPath().c_str()))
       {
       DoAccept<IsSameTag<Tag, HeaderSourcesTag>::Result>::Do(this->Data, sf);
@@ -205,10 +216,6 @@
     else
       {
       DoAccept<IsSameTag<Tag, ExtraSourcesTag>::Result>::Do(this->Data, sf);
-      if(this->IsObjLib && ext != "txt")
-        {
-        this->BadObjLibFiles.push_back(sf);
-        }
       }
   }
 };
@@ -252,7 +259,7 @@
   return 0;
 }
 
-static void handleSystemIncludesDep(cmMakefile *mf, cmTarget* depTgt,
+static void handleSystemIncludesDep(cmMakefile *mf, cmTarget const* depTgt,
                                   const std::string& config,
                                   cmTarget *headTarget,
                                   cmGeneratorExpressionDAGChecker *dagChecker,
@@ -432,6 +439,24 @@
 }
 
 //----------------------------------------------------------------------------
+void
+cmGeneratorTarget
+::GetAppManifest(std::vector<cmSourceFile const*>& data,
+                 const std::string& config) const
+{
+  IMPLEMENT_VISIT(AppManifest);
+}
+
+//----------------------------------------------------------------------------
+void
+cmGeneratorTarget
+::GetCertificates(std::vector<cmSourceFile const*>& data,
+                  const std::string& config) const
+{
+  IMPLEMENT_VISIT(Certificates);
+}
+
+//----------------------------------------------------------------------------
 bool cmGeneratorTarget::IsSystemIncludeDirectory(const std::string& dir,
                                               const std::string& config) const
 {
@@ -448,13 +473,6 @@
 
   if (iter == this->SystemIncludesCache.end())
     {
-    cmTarget::LinkImplementation const* impl
-                  = this->Target->GetLinkImplementation(config, this->Target);
-    if(!impl)
-      {
-      return false;
-      }
-
     cmGeneratorExpressionDAGChecker dagChecker(
                                         this->GetName(),
                                         "SYSTEM_INCLUDE_DIRECTORIES", 0, 0);
@@ -474,35 +492,15 @@
                                           &dagChecker), result);
       }
 
-    std::set<cmTarget*> uniqueDeps;
-    for(std::vector<std::string>::const_iterator li = impl->Libraries.begin();
-        li != impl->Libraries.end(); ++li)
+    std::vector<cmTarget const*> const& deps =
+      this->Target->GetLinkImplementationClosure(config);
+    for(std::vector<cmTarget const*>::const_iterator
+          li = deps.begin(), le = deps.end(); li != le; ++li)
       {
-      cmTarget* tgt = this->Makefile->FindTargetToUse(*li);
-      if (!tgt)
-        {
-        continue;
-        }
-
-      if (uniqueDeps.insert(tgt).second)
-        {
-        handleSystemIncludesDep(this->Makefile, tgt, config, this->Target,
-                                &dagChecker, result, excludeImported);
-
-        std::vector<cmTarget*> deps;
-        tgt->GetTransitivePropertyTargets(config, this->Target, deps);
-
-        for(std::vector<cmTarget*>::const_iterator di = deps.begin();
-            di != deps.end(); ++di)
-          {
-          if (uniqueDeps.insert(*di).second)
-            {
-            handleSystemIncludesDep(this->Makefile, *di, config, this->Target,
-                                    &dagChecker, result, excludeImported);
-            }
-          }
-        }
+      handleSystemIncludesDep(this->Makefile, *li, config, this->Target,
+                              &dagChecker, result, excludeImported);
       }
+
     std::set<std::string> unique;
     for(std::vector<std::string>::iterator li = result.begin();
         li != result.end(); ++li)
@@ -521,9 +519,7 @@
     iter = this->SystemIncludesCache.insert(entry).first;
     }
 
-  std::string dirString = dir;
-  return std::binary_search(iter->second.begin(), iter->second.end(),
-                            dirString);
+  return std::binary_search(iter->second.begin(), iter->second.end(), dir);
 }
 
 //----------------------------------------------------------------------------
diff --git a/Source/cmGeneratorTarget.h b/Source/cmGeneratorTarget.h
index 29aa410..2083b88 100644
--- a/Source/cmGeneratorTarget.h
+++ b/Source/cmGeneratorTarget.h
@@ -54,6 +54,10 @@
                          const std::string& config) const;
   void GetExpectedResxHeaders(std::set<std::string>&,
                               const std::string& config) const;
+  void GetAppManifest(std::vector<cmSourceFile const*>&,
+                      const std::string& config) const;
+  void GetCertificates(std::vector<cmSourceFile const*>&,
+                       const std::string& config) const;
 
   void ComputeObjectMapping();
 
diff --git a/Source/cmGetSourceFilePropertyCommand.cxx b/Source/cmGetSourceFilePropertyCommand.cxx
index 8a96289..7667a85 100644
--- a/Source/cmGetSourceFilePropertyCommand.cxx
+++ b/Source/cmGetSourceFilePropertyCommand.cxx
@@ -29,7 +29,7 @@
   // for the location we must create a source file first
   if (!sf && args[2] == "LOCATION")
     {
-    sf = this->Makefile->GetOrCreateSource(file);
+    sf = this->Makefile->CreateSource(file);
     }
   if(sf)
     {
diff --git a/Source/cmGlobalBorlandMakefileGenerator.h b/Source/cmGlobalBorlandMakefileGenerator.h
index 470dea4..120d2f8 100644
--- a/Source/cmGlobalBorlandMakefileGenerator.h
+++ b/Source/cmGlobalBorlandMakefileGenerator.h
@@ -39,7 +39,7 @@
   virtual cmLocalGenerator *CreateLocalGenerator();
 
   /**
-   * Try to determine system infomation such as shared library
+   * Try to determine system information such as shared library
    * extension, pthreads, byte order etc.
    */
   virtual void EnableLanguage(std::vector<std::string>const& languages,
diff --git a/Source/cmGlobalGenerator.cxx b/Source/cmGlobalGenerator.cxx
index 6c8be72..ae0e807 100644
--- a/Source/cmGlobalGenerator.cxx
+++ b/Source/cmGlobalGenerator.cxx
@@ -76,18 +76,46 @@
     }
 }
 
+bool cmGlobalGenerator::SetGeneratorPlatform(std::string const& p,
+                                             cmMakefile* mf)
+{
+  if(p.empty())
+    {
+    return true;
+    }
+  else
+    {
+    cmOStringStream e;
+    e <<
+      "Generator\n"
+      "  " << this->GetName() << "\n"
+      "does not support platform specification, but platform\n"
+      "  " << p << "\n"
+      "was specified.";
+    mf->IssueMessage(cmake::FATAL_ERROR, e.str());
+    return false;
+    }
+}
+
 bool cmGlobalGenerator::SetGeneratorToolset(std::string const& ts,
                                             cmMakefile* mf)
 {
-  cmOStringStream e;
-  e <<
-    "Generator\n"
-    "  " << this->GetName() << "\n"
-    "does not support toolset specification, but toolset\n"
-    "  " << ts << "\n"
-    "was specified.";
-  mf->IssueMessage(cmake::FATAL_ERROR, e.str());
-  return false;
+  if(ts.empty())
+    {
+    return true;
+    }
+  else
+    {
+    cmOStringStream e;
+    e <<
+      "Generator\n"
+      "  " << this->GetName() << "\n"
+      "does not support toolset specification, but toolset\n"
+      "  " << ts << "\n"
+      "was specified.";
+    mf->IssueMessage(cmake::FATAL_ERROR, e.str());
+    return false;
+    }
 }
 
 std::string cmGlobalGenerator::SelectMakeProgram(
@@ -148,8 +176,6 @@
     {
     return;
     }
-  std::string doc = lang;
-  doc += " compiler.";
   const char* cname = this->GetCMakeInstance()->
     GetCacheManager()->GetCacheValue(langComp);
   std::string changeVars;
@@ -186,8 +212,6 @@
         changeVars.c_str());
       }
     }
-  mf->AddCacheDefinition(langComp, path.c_str(),
-                         doc.c_str(), cmCacheManager::FILEPATH);
 }
 
 void cmGlobalGenerator::AddBuildExportSet(cmExportBuildFileGenerator* gen)
@@ -294,7 +318,7 @@
     // will run xcodebuild and if it sees the error text file busy
     // it will stop forwarding output, and let the build finish.
     // Then it will retry the build.  It will continue this
-    // untill no text file busy errors occur.
+    // until no text file busy errors occur.
     std::string cmakexbuild =
       this->CMakeInstance->GetCacheManager()->GetCacheValue("CMAKE_COMMAND");
     cmakexbuild = cmakexbuild.substr(0, cmakexbuild.length()-5);
@@ -414,7 +438,8 @@
 
   // try and load the CMakeSystem.cmake if it is there
   std::string fpath = rootBin;
-  if(!mf->GetDefinition("CMAKE_SYSTEM_LOADED"))
+  bool const readCMakeSystem = !mf->GetDefinition("CMAKE_SYSTEM_LOADED");
+  if(readCMakeSystem)
     {
     fpath += "/CMakeSystem.cmake";
     if(cmSystemTools::FileExists(fpath.c_str()))
@@ -448,13 +473,31 @@
     mf->ReadListFile(0,fpath.c_str());
     }
 
-  // Tell the generator about the toolset, if any.
-  std::string toolset = mf->GetSafeDefinition("CMAKE_GENERATOR_TOOLSET");
-  if(!toolset.empty() &&
-     !this->SetGeneratorToolset(toolset, mf))
+  if(readCMakeSystem)
     {
-    cmSystemTools::SetFatalErrorOccured();
-    return;
+    // Tell the generator about the target system.
+    std::string system = mf->GetSafeDefinition("CMAKE_SYSTEM_NAME");
+    if(!this->SetSystemName(system, mf))
+      {
+      cmSystemTools::SetFatalErrorOccured();
+      return;
+      }
+
+    // Tell the generator about the platform, if any.
+    std::string platform = mf->GetSafeDefinition("CMAKE_GENERATOR_PLATFORM");
+    if(!this->SetGeneratorPlatform(platform, mf))
+      {
+      cmSystemTools::SetFatalErrorOccured();
+      return;
+      }
+
+    // Tell the generator about the toolset, if any.
+    std::string toolset = mf->GetSafeDefinition("CMAKE_GENERATOR_TOOLSET");
+    if(!this->SetGeneratorToolset(toolset, mf))
+      {
+      cmSystemTools::SetFatalErrorOccured();
+      return;
+      }
     }
 
   // **** Load the system specific initialization if not yet loaded
@@ -463,8 +506,8 @@
     fpath = mf->GetModulesFile("CMakeSystemSpecificInitialize.cmake");
     if(!mf->ReadListFile(0,fpath.c_str()))
       {
-      cmSystemTools::Error("Could not find cmake module file: ",
-                           fpath.c_str());
+      cmSystemTools::Error("Could not find cmake module file: "
+                           "CMakeSystemSpecificInitialize.cmake");
       }
     }
 
@@ -532,7 +575,7 @@
       if(!mf->ReadListFile(0,determineFile.c_str()))
         {
         cmSystemTools::Error("Could not find cmake module file: ",
-                             determineFile.c_str());
+                             determineCompiler.c_str());
         }
       needTestLanguage[lang] = true;
       // Some generators like visual studio should not use the env variables
@@ -584,8 +627,8 @@
     fpath = mf->GetModulesFile("CMakeSystemSpecificInformation.cmake");
     if(!mf->ReadListFile(0,fpath.c_str()))
       {
-      cmSystemTools::Error("Could not find cmake module file: ",
-                           fpath.c_str());
+      cmSystemTools::Error("Could not find cmake module file: "
+                           "CMakeSystemSpecificInformation.cmake");
       }
     }
   // loop over languages again loading CMake(LANG)Information.cmake
@@ -616,7 +659,8 @@
         "No " << compilerName << " could be found.\n"
         ;
       }
-    else if(strcmp(lang, "RC") != 0)
+    else if(strcmp(lang, "RC") != 0 &&
+            strcmp(lang, "ASM_MASM") != 0)
       {
       if(!cmSystemTools::FileIsFullPath(compilerFile))
         {
@@ -700,7 +744,7 @@
         if(!mf->ReadListFile(0,ifpath.c_str()))
           {
           cmSystemTools::Error("Could not find cmake module file: ",
-                               ifpath.c_str());
+                               testLang.c_str());
           }
         std::string compilerWorks = "CMAKE_";
         compilerWorks += lang;
@@ -840,6 +884,14 @@
       case cmPolicies::OLD:
         // OLD behavior is to convert QCC to GNU.
         mf->AddDefinition(compilerIdVar, "GNU");
+        if(lang == "C")
+          {
+          mf->AddDefinition("CMAKE_COMPILER_IS_GNUCC", "1");
+          }
+        else if(lang == "CXX")
+          {
+          mf->AddDefinition("CMAKE_COMPILER_IS_GNUCXX", "1");
+          }
         break;
       case cmPolicies::REQUIRED_IF_USED:
       case cmPolicies::REQUIRED_ALWAYS:
@@ -956,9 +1008,9 @@
     if (sscanf(linkerPref, "%d", &preference)!=1)
       {
       // backward compatibility: before 2.6 LINKER_PREFERENCE
-      // was either "None" or "Prefered", and only the first character was
+      // was either "None" or "Preferred", and only the first character was
       // tested. So if there is a custom language out there and it is
-      // "Prefered", set its preference high
+      // "Preferred", set its preference high
       if (linkerPref[0]=='P')
         {
         preference = 100;
@@ -1045,36 +1097,6 @@
   this->LanguageEnabled.clear();
 }
 
-bool cmGlobalGenerator::IsDependedOn(const std::string& project,
-                                     cmTarget const* targetIn)
-{
-  // Get all local gens for this project
-  std::map<std::string, std::vector<cmLocalGenerator*> >::const_iterator it =
-                                              this->ProjectMap.find(project);
-  if (it == this->ProjectMap.end())
-    {
-    return false;
-    }
-
-  // loop over local gens and get the targets for each one
-  for(std::vector<cmLocalGenerator*>::const_iterator geIt = it->second.begin();
-      geIt != it->second.end(); ++geIt)
-    {
-    cmTargets const& targets = (*geIt)->GetMakefile()->GetTargets();
-    for (cmTargets::const_iterator l = targets.begin();
-         l != targets.end(); l++)
-      {
-      cmTarget const& target = l->second;
-      TargetDependSet const& tgtdeps = this->GetTargetDirectDepends(target);
-      if(tgtdeps.count(targetIn))
-        {
-        return true;
-        }
-      }
-    }
-  return false;
-}
-
 void cmGlobalGenerator::Configure()
 {
   this->FirstTimeProgress = 0.0f;
@@ -1175,7 +1197,7 @@
   return false;
 }
 
-void cmGlobalGenerator::Generate()
+void cmGlobalGenerator::DoGenerate()
 {
   // Some generators track files replaced during the Generate.
   // Start with an empty vector:
@@ -1184,6 +1206,11 @@
   // clear targets to issue warning CMP0042 for
   this->CMP0042WarnTargets.clear();
 
+  this->Generate();
+}
+
+void cmGlobalGenerator::Generate()
+{
   // Check whether this generator is allowed to run.
   if(!this->CheckALLOW_DUPLICATE_CUSTOM_TARGETS())
     {
@@ -1637,7 +1664,7 @@
                                   const std::string& bindir,
                                   const std::string& projectName,
                                   const std::string& target, bool fast,
-                                  std::string *output, cmMakefile *mf)
+                                  std::string& output, cmMakefile *mf)
 {
   // if this is not set, then this is a first time configure
   // and there is a good chance that the try compile stuff will
@@ -1696,7 +1723,7 @@
 int cmGlobalGenerator::Build(
   const std::string&, const std::string& bindir,
   const std::string& projectName, const std::string& target,
-  std::string *output,
+  std::string& output,
   const std::string& makeCommandCSTR,
   const std::string& config,
   bool clean, bool fast,
@@ -1709,22 +1736,15 @@
    */
   std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
   cmSystemTools::ChangeDirectory(bindir.c_str());
-  if(output)
-    {
-    *output += "Change Dir: ";
-    *output += bindir;
-    *output += "\n";
-    }
+  output += "Change Dir: ";
+  output += bindir;
+  output += "\n";
 
   int retVal;
   bool hideconsole = cmSystemTools::GetRunCommandHideConsole();
   cmSystemTools::SetRunCommandHideConsole(true);
   std::string outputBuffer;
-  std::string* outputPtr = 0;
-  if(output)
-    {
-    outputPtr = &outputBuffer;
-    }
+  std::string* outputPtr = &outputBuffer;
 
   // should we do a clean first?
   if (clean)
@@ -1732,32 +1752,23 @@
     std::vector<std::string> cleanCommand;
     this->GenerateBuildCommand(cleanCommand, makeCommandCSTR, projectName,
                                bindir, "clean", config, fast);
-    if(output)
-      {
-      *output += "\nRun Clean Command:";
-      *output += cmSystemTools::PrintSingleCommand(cleanCommand);
-      *output += "\n";
-      }
+    output += "\nRun Clean Command:";
+    output += cmSystemTools::PrintSingleCommand(cleanCommand);
+    output += "\n";
 
     if (!cmSystemTools::RunSingleCommand(cleanCommand, outputPtr,
                                          &retVal, 0, outputflag, timeout))
       {
       cmSystemTools::SetRunCommandHideConsole(hideconsole);
       cmSystemTools::Error("Generator: execution of make clean failed.");
-      if (output)
-        {
-        *output += *outputPtr;
-        *output += "\nGenerator: execution of make clean failed.\n";
-        }
+      output += *outputPtr;
+      output += "\nGenerator: execution of make clean failed.\n";
 
       // return to the original directory
       cmSystemTools::ChangeDirectory(cwd.c_str());
       return 1;
       }
-    if (output)
-      {
-      *output += *outputPtr;
-      }
+    output += *outputPtr;
     }
 
   // now build
@@ -1765,12 +1776,9 @@
   this->GenerateBuildCommand(makeCommand, makeCommandCSTR, projectName,
                              bindir, target, config, fast, nativeOptions);
   std::string makeCommandStr = cmSystemTools::PrintSingleCommand(makeCommand);
-  if(output)
-    {
-    *output += "\nRun Build Command:";
-    *output += makeCommandStr;
-    *output += "\n";
-    }
+  output += "\nRun Build Command:";
+  output += makeCommandStr;
+  output += "\n";
 
   if (!cmSystemTools::RunSingleCommand(makeCommand, outputPtr,
                                        &retVal, 0, outputflag, timeout))
@@ -1779,27 +1787,21 @@
     cmSystemTools::Error
       ("Generator: execution of make failed. Make command was: ",
        makeCommandStr.c_str());
-    if (output)
-      {
-      *output += *outputPtr;
-      *output += "\nGenerator: execution of make failed. Make command was: "
+    output += *outputPtr;
+    output += "\nGenerator: execution of make failed. Make command was: "
         + makeCommandStr + "\n";
-      }
 
     // return to the original directory
     cmSystemTools::ChangeDirectory(cwd.c_str());
     return 1;
     }
-  if (output)
-    {
-    *output += *outputPtr;
-    }
+  output += *outputPtr;
   cmSystemTools::SetRunCommandHideConsole(hideconsole);
 
   // The SGI MipsPro 7.3 compiler does not return an error code when
   // the source has a #error in it!  This is a work-around for such
   // compilers.
-  if((retVal == 0) && (output->find("#error") != std::string::npos))
+  if((retVal == 0) && (output.find("#error") != std::string::npos))
     {
     retVal = 1;
     }
diff --git a/Source/cmGlobalGenerator.h b/Source/cmGlobalGenerator.h
index 67bd378..ddd7e91 100644
--- a/Source/cmGlobalGenerator.h
+++ b/Source/cmGlobalGenerator.h
@@ -39,7 +39,7 @@
 class cmQtAutoGenerators;
 
 /** \class cmGlobalGenerator
- * \brief Responable for overseeing the generation process for the entire tree
+ * \brief Responsible for overseeing the generation process for the entire tree
  *
  * Subclasses of this class generate makefiles for various
  * platforms.
@@ -61,6 +61,14 @@
   virtual bool MatchesGeneratorName(const std::string& name) const
   { return this->GetName() == name; }
 
+  /** Tell the generator about the target system.  */
+  virtual bool SetSystemName(std::string const&, cmMakefile*)
+    { return true; }
+
+  /** Set the generator-specific platform name.  Returns true if platform
+      is supported and false otherwise.  */
+  virtual bool SetGeneratorPlatform(std::string const& p, cmMakefile* mf);
+
   /** Set the generator-specific toolset name.  Returns true if toolset
       is supported and false otherwise.  */
   virtual bool SetGeneratorToolset(std::string const& ts, cmMakefile* mf);
@@ -76,7 +84,7 @@
    * basically creates a series of LocalGenerators for each directory and
    * requests that they Generate.
    */
-  virtual void Generate();
+  void DoGenerate();
 
   /**
    * Set/Get and Clear the enabled languages.
@@ -86,7 +94,7 @@
   void ClearEnabledLanguages();
   void GetEnabledLanguages(std::vector<std::string>& lang) const;
   /**
-   * Try to determine system infomation such as shared library
+   * Try to determine system information such as shared library
    * extension, pthreads, byte order etc.
    */
   virtual void EnableLanguage(std::vector<std::string>const& languages,
@@ -100,7 +108,7 @@
                                bool optional) const;
 
   /**
-   * Try to determine system infomation, get it from another generator
+   * Try to determine system information, get it from another generator
    */
   virtual void EnableLanguagesFromGenerator(cmGlobalGenerator *gen,
                                             cmMakefile* mf);
@@ -112,7 +120,7 @@
   virtual int TryCompile(const std::string& srcdir, const std::string& bindir,
                          const std::string& projectName,
                          const std::string& targetName,
-                         bool fast, std::string *output, cmMakefile* mf);
+                         bool fast, std::string& output, cmMakefile* mf);
 
 
   /**
@@ -123,7 +131,7 @@
    */
   int Build(const std::string& srcdir, const std::string& bindir,
             const std::string& projectName, const std::string& targetName,
-            std::string *output,
+            std::string& output,
             const std::string& makeProgram, const std::string& config,
             bool clean, bool fast,
             double timeout,
@@ -190,7 +198,7 @@
   std::string GetLanguageFromExtension(const char* ext) const;
   ///! is an extension to be ignored
   bool IgnoreFile(const char* ext) const;
-  ///! What is the preference for linkers and this language (None or Prefered)
+  ///! What is the preference for linkers and this language (None or Preferred)
   int GetLinkerPreference(const std::string& lang) const;
   ///! What is the object file extension for a given source file?
   std::string GetLanguageOutputExtension(cmSourceFile const&) const;
@@ -214,6 +222,11 @@
    */
   virtual void FindMakeProgram(cmMakefile*);
 
+#if defined(_WIN32) && !defined(__CYGWIN__)
+  /** Is this the Visual Studio 6 generator?  */
+  virtual bool IsForVS6() const { return false; }
+#endif
+
   ///! Find a target by name by searching the local generators.
   cmTarget* FindTarget(const std::string& name,
                        bool excludeAliases = false) const;
@@ -225,9 +238,6 @@
       that is a framework. */
   bool NameResolvesToFramework(const std::string& libname) const;
 
-  /** If check to see if the target is linked to by any other
-      target in the project */
-  bool IsDependedOn(const std::string& project, cmTarget const* target);
   ///! Find a local generator by its startdirectory
   cmLocalGenerator* FindLocalGenerator(const std::string& start_dir) const;
 
@@ -332,6 +342,8 @@
   bool GenerateCPackPropertiesFile();
 
 protected:
+  virtual void Generate();
+
   typedef std::vector<cmLocalGenerator*> GeneratorVector;
   // for a project collect all its targets by following depend
   // information, and also collect all the targets
diff --git a/Source/cmGlobalJOMMakefileGenerator.h b/Source/cmGlobalJOMMakefileGenerator.h
index 344e013..fbb35f3 100644
--- a/Source/cmGlobalJOMMakefileGenerator.h
+++ b/Source/cmGlobalJOMMakefileGenerator.h
@@ -40,7 +40,7 @@
   virtual cmLocalGenerator *CreateLocalGenerator();
 
   /**
-   * Try to determine system infomation such as shared library
+   * Try to determine system information such as shared library
    * extension, pthreads, byte order etc.
    */
   virtual void EnableLanguage(std::vector<std::string>const& languages,
diff --git a/Source/cmGlobalMSYSMakefileGenerator.h b/Source/cmGlobalMSYSMakefileGenerator.h
index c4825bd..baecde7 100644
--- a/Source/cmGlobalMSYSMakefileGenerator.h
+++ b/Source/cmGlobalMSYSMakefileGenerator.h
@@ -39,7 +39,7 @@
   virtual cmLocalGenerator *CreateLocalGenerator();
 
   /**
-   * Try to determine system infomation such as shared library
+   * Try to determine system information such as shared library
    * extension, pthreads, byte order etc.
    */
   virtual void EnableLanguage(std::vector<std::string>const& languages,
diff --git a/Source/cmGlobalMinGWMakefileGenerator.h b/Source/cmGlobalMinGWMakefileGenerator.h
index 4289422..fa8d9f2 100644
--- a/Source/cmGlobalMinGWMakefileGenerator.h
+++ b/Source/cmGlobalMinGWMakefileGenerator.h
@@ -38,7 +38,7 @@
   virtual cmLocalGenerator *CreateLocalGenerator();
 
   /**
-   * Try to determine system infomation such as shared library
+   * Try to determine system information such as shared library
    * extension, pthreads, byte order etc.
    */
   virtual void EnableLanguage(std::vector<std::string>const& languages,
diff --git a/Source/cmGlobalNMakeMakefileGenerator.h b/Source/cmGlobalNMakeMakefileGenerator.h
index 2ff44e3..e7b03dd 100644
--- a/Source/cmGlobalNMakeMakefileGenerator.h
+++ b/Source/cmGlobalNMakeMakefileGenerator.h
@@ -38,7 +38,7 @@
   virtual cmLocalGenerator *CreateLocalGenerator();
 
   /**
-   * Try to determine system infomation such as shared library
+   * Try to determine system information such as shared library
    * extension, pthreads, byte order etc.
    */
   virtual void EnableLanguage(std::vector<std::string>const& languages,
diff --git a/Source/cmGlobalNinjaGenerator.cxx b/Source/cmGlobalNinjaGenerator.cxx
index a0caf0e..6e7b06b 100644
--- a/Source/cmGlobalNinjaGenerator.cxx
+++ b/Source/cmGlobalNinjaGenerator.cxx
@@ -151,11 +151,6 @@
       ++i)
     {
     arguments += " " + EncodeIdent(EncodePath(*i), os);
-
-    //we need to track every dependency that comes in, since we are trying
-    //to find dependencies that are side effects of build commands
-    //
-    this->CombinedBuildExplicitDependencies.insert( EncodePath(*i) );
     }
 
   // Write implicit dependencies.
@@ -210,7 +205,7 @@
       && args.size() + buildstr.size() + assignments.size()
                                                     > (size_t) cmdLineLimit) {
     buildstr += "_RSP_FILE";
-    variable_assignments.clear();
+    variable_assignments.str(std::string());
     cmGlobalNinjaGenerator::WriteVariable(variable_assignments,
                                           "RSP_FILE", rspfile, "", 1);
     assignments += variable_assignments.str();
@@ -280,6 +275,13 @@
                    cmNinjaDeps(),
                    orderOnly,
                    vars);
+
+  //we need to track every dependency that comes in, since we are trying
+  //to find dependencies that are side effects of build commands
+  for(cmNinjaDeps::const_iterator i = deps.begin(); i != deps.end(); ++i)
+    {
+    this->CombinedCustomCommandExplicitDependencies.insert( EncodePath(*i) );
+    }
 }
 
 void
@@ -538,6 +540,15 @@
     cmSystemTools::Error("The Ninja generator does not support Fortran yet.");
     }
   this->cmGlobalGenerator::EnableLanguage(langs, makefile, optional);
+  for(std::vector<std::string>::const_iterator l = langs.begin();
+      l != langs.end(); ++l)
+    {
+    if(*l == "NONE")
+      {
+      continue;
+      }
+    this->ResolveLanguageCompiler(*l, makefile, optional);
+    }
 }
 
 bool cmGlobalNinjaGenerator::UsingMinGW = false;
@@ -961,7 +972,16 @@
       {
       knownDependencies.insert( ng->ConvertToNinjaPath( j->c_str() ) );
       }
+    //get list files which are implicit dependencies as well and will be phony
+    //for rebuild manifest
+    std::vector<std::string> const& lf = (*i)->GetMakefile()->GetListFiles();
+    typedef std::vector<std::string>::const_iterator vect_it;
+    for(vect_it j = lf.begin(); j != lf.end(); ++j)
+      {
+      knownDependencies.insert( ng->ConvertToNinjaPath( j->c_str() ) );
+      }
     }
+  knownDependencies.insert( "CMakeCache.txt" );
 
   for(std::vector<cmGeneratorExpressionEvaluationFile*>::const_iterator
       li = this->EvaluationFiles.begin();
@@ -1006,17 +1026,17 @@
   //to keep this data around
   this->CombinedBuildOutputs.clear();
 
-  //now we difference with CombinedBuildExplicitDependencies to find
+  //now we difference with CombinedCustomCommandExplicitDependencies to find
   //the list of items we know nothing about.
-  //We have encoded all the paths in CombinedBuildExplicitDependencies
+  //We have encoded all the paths in CombinedCustomCommandExplicitDependencies
   //and knownDependencies so no matter if unix or windows paths they
   //should all match now.
 
   std::vector<std::string> unkownExplicitDepends;
-  this->CombinedBuildExplicitDependencies.erase("all");
+  this->CombinedCustomCommandExplicitDependencies.erase("all");
 
-  std::set_difference(this->CombinedBuildExplicitDependencies.begin(),
-                      this->CombinedBuildExplicitDependencies.end(),
+  std::set_difference(this->CombinedCustomCommandExplicitDependencies.begin(),
+                      this->CombinedCustomCommandExplicitDependencies.end(),
                       knownDependencies.begin(),
                       knownDependencies.end(),
                       std::back_inserter(unkownExplicitDepends));
@@ -1118,6 +1138,16 @@
   implicitDeps.erase(std::unique(implicitDeps.begin(), implicitDeps.end()),
                      implicitDeps.end());
 
+  cmNinjaVars variables;
+  // Use 'console' pool to get non buffered output of the CMake re-run call
+  // Available since Ninja 1.5
+  if(cmSystemTools::VersionCompare(cmSystemTools::OP_LESS,
+                                   ninjaVersion().c_str(),
+                                   "1.5") == false)
+    {
+    variables["pool"] = "console";
+    }
+
   this->WriteBuild(os,
                    "Re-run CMake if any of its inputs changed.",
                    "RERUN_CMAKE",
@@ -1125,7 +1155,7 @@
                    /*explicitDeps=*/ cmNinjaDeps(),
                    implicitDeps,
                    /*orderOnlyDeps=*/ cmNinjaDeps(),
-                   /*variables=*/ cmNinjaVars());
+                   variables);
 
   this->WritePhonyBuild(os,
                         "A missing CMake input file is not an error.",
@@ -1144,6 +1174,17 @@
   return "ninja";
 }
 
+std::string cmGlobalNinjaGenerator::ninjaVersion() const
+{
+  std::string version;
+  std::string command = ninjaCmd() + " --version";
+  cmSystemTools::RunSingleCommand(command.c_str(),
+                                  &version, 0, 0,
+                                  cmSystemTools::OUTPUT_NONE);
+
+  return version;
+}
+
 void cmGlobalNinjaGenerator::WriteTargetClean(std::ostream& os)
 {
   WriteRule(*this->RulesFileStream,
diff --git a/Source/cmGlobalNinjaGenerator.h b/Source/cmGlobalNinjaGenerator.h
index f2643af..f666ee3 100644
--- a/Source/cmGlobalNinjaGenerator.h
+++ b/Source/cmGlobalNinjaGenerator.h
@@ -182,9 +182,6 @@
   /// Overloaded methods. @see cmGlobalGenerator::GetDocumentation()
   static void GetDocumentation(cmDocumentationEntry& entry);
 
-  /// Overloaded methods. @see cmGlobalGenerator::Generate()
-  virtual void Generate();
-
   /// Overloaded methods. @see cmGlobalGenerator::EnableLanguage()
   virtual void EnableLanguage(std::vector<std::string>const& languages,
                               cmMakefile* mf,
@@ -300,8 +297,13 @@
   void AddTargetAlias(const std::string& alias, cmTarget* target);
 
   virtual void ComputeTargetObjectDirectory(cmGeneratorTarget* gt) const;
+
+  std::string ninjaVersion() const;
 protected:
 
+  /// Overloaded methods. @see cmGlobalGenerator::Generate()
+  virtual void Generate();
+
   /// Overloaded methods.
   /// @see cmGlobalGenerator::CheckALLOW_DUPLICATE_CUSTOM_TARGETS()
   virtual bool CheckALLOW_DUPLICATE_CUSTOM_TARGETS() const { return true; }
@@ -335,8 +337,7 @@
 
   std::string ninjaCmd() const;
 
-
-  /// The file containing the build statement. (the relation ship of the
+  /// The file containing the build statement. (the relationship of the
   /// compilation DAG).
   cmGeneratedFileStream* BuildFileStream;
   /// The file containing the rule statements. (The action attached to each
@@ -363,10 +364,11 @@
   /// The set of custom command outputs we have seen.
   std::set<std::string> CustomCommandOutputs;
 
-  //The combined explicit dependencies of all build commands that the global
-  //generator has issued. When combined with CombinedBuildOutputs it allows
-  //us to detect the set of explicit dependencies that have
-  std::set<std::string> CombinedBuildExplicitDependencies;
+  /// The combined explicit dependencies of custom build commands
+  std::set<std::string> CombinedCustomCommandExplicitDependencies;
+
+  /// When combined with CombinedCustomCommandExplicitDependencies it allows
+  /// us to detect the set of explicit dependencies that have
   std::set<std::string> CombinedBuildOutputs;
 
   /// The mapping from source file to assumed dependencies.
diff --git a/Source/cmGlobalUnixMakefileGenerator3.cxx b/Source/cmGlobalUnixMakefileGenerator3.cxx
index 8dae81b..3478534 100644
--- a/Source/cmGlobalUnixMakefileGenerator3.cxx
+++ b/Source/cmGlobalUnixMakefileGenerator3.cxx
@@ -530,7 +530,7 @@
   // Begin the directory-level rules section.
   std::string dir = lg->GetMakefile()->GetStartOutputDirectory();
   dir = lg->Convert(dir, cmLocalGenerator::HOME_OUTPUT,
-                    cmLocalGenerator::MAKEFILE);
+                    cmLocalGenerator::MAKERULE);
   lg->WriteDivider(ruleFileStream);
   ruleFileStream
     << "# Directory level rules for directory "
diff --git a/Source/cmGlobalUnixMakefileGenerator3.h b/Source/cmGlobalUnixMakefileGenerator3.h
index f44dd12..c61c36e 100644
--- a/Source/cmGlobalUnixMakefileGenerator3.h
+++ b/Source/cmGlobalUnixMakefileGenerator3.h
@@ -71,7 +71,7 @@
   virtual cmLocalGenerator *CreateLocalGenerator();
 
   /**
-   * Try to determine system infomation such as shared library
+   * Try to determine system information such as shared library
    * extension, pthreads, byte order etc.
    */
   virtual void EnableLanguage(std::vector<std::string>const& languages,
diff --git a/Source/cmGlobalVisualStudio10Generator.cxx b/Source/cmGlobalVisualStudio10Generator.cxx
index 86d0de3..d70d2af 100644
--- a/Source/cmGlobalVisualStudio10Generator.cxx
+++ b/Source/cmGlobalVisualStudio10Generator.cxx
@@ -48,20 +48,22 @@
     const char* p = cmVS10GenName(name, genName);
     if(!p)
       { return 0; }
-    if(strcmp(p, "") == 0)
+    if(!*p)
       {
       return new cmGlobalVisualStudio10Generator(
-        genName, "", "");
+        genName, "");
       }
-    if(strcmp(p, " Win64") == 0)
+    if(*p++ != ' ')
+      { return 0; }
+    if(strcmp(p, "Win64") == 0)
       {
       return new cmGlobalVisualStudio10Generator(
-        genName, "x64", "CMAKE_FORCE_WIN64");
+        genName, "x64");
       }
-    if(strcmp(p, " IA64") == 0)
+    if(strcmp(p, "IA64") == 0)
       {
       return new cmGlobalVisualStudio10Generator(
-        genName, "Itanium", "CMAKE_FORCE_IA64");
+        genName, "Itanium");
       }
     return 0;
     }
@@ -88,16 +90,16 @@
 
 //----------------------------------------------------------------------------
 cmGlobalVisualStudio10Generator::cmGlobalVisualStudio10Generator(
-  const std::string& name, const std::string& platformName,
-  const std::string& additionalPlatformDefinition)
-  : cmGlobalVisualStudio8Generator(name, platformName,
-                                   additionalPlatformDefinition)
+  const std::string& name, const std::string& platformName)
+  : cmGlobalVisualStudio8Generator(name, platformName)
 {
   std::string vc10Express;
   this->ExpressEdition = cmSystemTools::ReadRegistryValue(
     "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VCExpress\\10.0\\Setup\\VC;"
     "ProductDir", vc10Express, cmSystemTools::KeyWOW64_32);
-  this->MasmEnabled = false;
+  this->SystemIsWindowsCE = false;
+  this->SystemIsWindowsPhone = false;
+  this->SystemIsWindowsStore = false;
   this->MSBuildCommandInitialized = false;
 }
 
@@ -115,30 +117,158 @@
 }
 
 //----------------------------------------------------------------------------
-bool
-cmGlobalVisualStudio10Generator::SetGeneratorToolset(std::string const& ts,
-                                                     cmMakefile* mf)
+bool cmGlobalVisualStudio10Generator::SetSystemName(std::string const& s,
+                                                    cmMakefile* mf)
 {
-  this->GeneratorToolset = ts;
-  this->AddVSPlatformToolsetDefinition(mf);
+  this->SystemName = s;
+  this->SystemVersion = mf->GetSafeDefinition("CMAKE_SYSTEM_VERSION");
+  if(!this->InitializeSystem(mf))
+    {
+    return false;
+    }
+  return this->cmGlobalVisualStudio8Generator::SetSystemName(s, mf);
+}
+
+//----------------------------------------------------------------------------
+bool
+cmGlobalVisualStudio10Generator::SetGeneratorPlatform(std::string const& p,
+                                                      cmMakefile* mf)
+{
+  if(!this->cmGlobalVisualStudio8Generator::SetGeneratorPlatform(p, mf))
+    {
+    return false;
+    }
+  if(this->GetPlatformName() == "Itanium" || this->GetPlatformName() == "x64")
+    {
+    if(this->IsExpressEdition() && !this->Find64BitTools(mf))
+      {
+      return false;
+      }
+    }
   return true;
 }
 
 //----------------------------------------------------------------------------
-void cmGlobalVisualStudio10Generator::AddPlatformDefinitions(cmMakefile* mf)
+bool
+cmGlobalVisualStudio10Generator::SetGeneratorToolset(std::string const& ts,
+                                                     cmMakefile* mf)
 {
-  cmGlobalVisualStudio8Generator::AddPlatformDefinitions(mf);
-  this->AddVSPlatformToolsetDefinition(mf);
-}
+  if (this->SystemIsWindowsCE && ts.empty() &&
+      this->DefaultPlatformToolset.empty())
+    {
+    cmOStringStream e;
+    e << this->GetName() << " Windows CE version '" << this->SystemVersion
+      << "' requires CMAKE_GENERATOR_TOOLSET to be set.";
+    mf->IssueMessage(cmake::FATAL_ERROR, e.str());
+    return false;
+    }
 
-//----------------------------------------------------------------------------
-void cmGlobalVisualStudio10Generator
-::AddVSPlatformToolsetDefinition(cmMakefile* mf) const
-{
+  this->GeneratorToolset = ts;
   if(const char* toolset = this->GetPlatformToolset())
     {
     mf->AddDefinition("CMAKE_VS_PLATFORM_TOOLSET", toolset);
     }
+  return true;
+}
+
+//----------------------------------------------------------------------------
+bool cmGlobalVisualStudio10Generator::InitializeSystem(cmMakefile* mf)
+{
+  if (this->SystemName == "WindowsCE")
+    {
+    this->SystemIsWindowsCE = true;
+    if (!this->InitializeWindowsCE(mf))
+      {
+      return false;
+      }
+    }
+  else if(this->SystemName == "WindowsPhone")
+    {
+    this->SystemIsWindowsPhone = true;
+    if(!this->InitializeWindowsPhone(mf))
+      {
+      return false;
+      }
+    }
+  else if(this->SystemName == "WindowsStore")
+    {
+    this->SystemIsWindowsStore = true;
+    if(!this->InitializeWindowsStore(mf))
+      {
+      return false;
+      }
+    }
+  else if(this->SystemName == "Android")
+    {
+    if(this->DefaultPlatformName != "Win32")
+      {
+      cmOStringStream e;
+      e << "CMAKE_SYSTEM_NAME is 'Android' but CMAKE_GENERATOR "
+        << "specifies a platform too: '" << this->GetName() << "'";
+      mf->IssueMessage(cmake::FATAL_ERROR, e.str());
+      return false;
+      }
+    std::string v = this->GetInstalledNsightTegraVersion();
+    if(v.empty())
+      {
+      mf->IssueMessage(cmake::FATAL_ERROR,
+        "CMAKE_SYSTEM_NAME is 'Android' but "
+        "'NVIDIA Nsight Tegra Visual Studio Edition' "
+        "is not installed.");
+      return false;
+      }
+    this->DefaultPlatformName = "Tegra-Android";
+    this->DefaultPlatformToolset = "Default";
+    this->NsightTegraVersion = v;
+    mf->AddDefinition("CMAKE_VS_NsightTegra_VERSION", v.c_str());
+    }
+
+  return true;
+}
+
+//----------------------------------------------------------------------------
+bool cmGlobalVisualStudio10Generator::InitializeWindowsCE(cmMakefile* mf)
+{
+  if (this->DefaultPlatformName != "Win32")
+    {
+    cmOStringStream e;
+    e << "CMAKE_SYSTEM_NAME is 'WindowsCE' but CMAKE_GENERATOR "
+      << "specifies a platform too: '" << this->GetName() << "'";
+    mf->IssueMessage(cmake::FATAL_ERROR, e.str());
+    return false;
+    }
+
+  this->DefaultPlatformToolset = this->SelectWindowsCEToolset();
+
+  return true;
+}
+
+//----------------------------------------------------------------------------
+bool cmGlobalVisualStudio10Generator::InitializeWindowsPhone(cmMakefile* mf)
+{
+  cmOStringStream e;
+  e << this->GetName() << " does not support Windows Phone.";
+  mf->IssueMessage(cmake::FATAL_ERROR, e.str());
+  return false;
+}
+
+//----------------------------------------------------------------------------
+bool cmGlobalVisualStudio10Generator::InitializeWindowsStore(cmMakefile* mf)
+{
+  cmOStringStream e;
+  e << this->GetName() << " does not support Windows Store.";
+  mf->IssueMessage(cmake::FATAL_ERROR, e.str());
+  return false;
+}
+
+//----------------------------------------------------------------------------
+std::string cmGlobalVisualStudio10Generator::SelectWindowsCEToolset() const
+{
+  if (this->SystemVersion == "8.0")
+    {
+    return "CE800";
+    }
+  return "";
 }
 
 //----------------------------------------------------------------------------
@@ -160,7 +290,6 @@
 {
   cmLocalVisualStudio10Generator* lg =
     new cmLocalVisualStudio10Generator(cmLocalVisualStudioGenerator::VS10);
-  lg->SetPlatformName(this->GetPlatformName());
   lg->SetGlobalGenerator(this);
   return lg;
 }
@@ -202,23 +331,6 @@
 ::EnableLanguage(std::vector<std::string>const &  lang,
                  cmMakefile *mf, bool optional)
 {
-  if(this->PlatformName == "Itanium" || this->PlatformName == "x64")
-    {
-    if(this->IsExpressEdition() && !this->Find64BitTools(mf))
-      {
-      return;
-      }
-    }
-
-  for(std::vector<std::string>::const_iterator it = lang.begin();
-      it != lang.end(); ++it)
-    {
-    if(*it == "ASM_MASM")
-      {
-      this->MasmEnabled = true;
-      }
-    }
-
   cmGlobalVisualStudio8Generator::EnableLanguage(lang, mf, optional);
 }
 
@@ -436,7 +548,7 @@
   // This edition does not come with 64-bit tools.  Look for them.
   //
   // TODO: Detect available tools?  x64\v100 exists but does not work?
-  // KHLM\\SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\\4.0;VCTargetsPath
+  // HKLM\\SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\\4.0;VCTargetsPath
   // c:/Program Files (x86)/MSBuild/Microsoft.Cpp/v4.0/Platforms/
   //   {Itanium,Win32,x64}/PlatformToolsets/{v100,v90,Windows7.1SDK}
   std::string winSDK_7_1;
@@ -500,3 +612,25 @@
 {
   return IsExpressEdition() ? false : cmGlobalGenerator::UseFolderProperty();
 }
+
+//----------------------------------------------------------------------------
+bool cmGlobalVisualStudio10Generator::IsNsightTegra() const
+{
+  return !this->NsightTegraVersion.empty();
+}
+
+//----------------------------------------------------------------------------
+std::string cmGlobalVisualStudio10Generator::GetNsightTegraVersion() const
+{
+  return this->NsightTegraVersion;
+}
+
+//----------------------------------------------------------------------------
+std::string cmGlobalVisualStudio10Generator::GetInstalledNsightTegraVersion()
+{
+  std::string version;
+  cmSystemTools::ReadRegistryValue(
+    "HKEY_LOCAL_MACHINE\\SOFTWARE\\NVIDIA Corporation\\Nsight Tegra;"
+    "Version", version, cmSystemTools::KeyWOW64_32);
+  return version;
+}
diff --git a/Source/cmGlobalVisualStudio10Generator.h b/Source/cmGlobalVisualStudio10Generator.h
index b4dcc7e..686dcdf 100644
--- a/Source/cmGlobalVisualStudio10Generator.h
+++ b/Source/cmGlobalVisualStudio10Generator.h
@@ -25,12 +25,13 @@
 {
 public:
   cmGlobalVisualStudio10Generator(const std::string& name,
-    const std::string& platformName,
-    const std::string& additionalPlatformDefinition);
+    const std::string& platformName);
   static cmGlobalGeneratorFactory* NewFactory();
 
   virtual bool MatchesGeneratorName(const std::string& name) const;
 
+  virtual bool SetSystemName(std::string const& s, cmMakefile* mf);
+  virtual bool SetGeneratorPlatform(std::string const& p, cmMakefile* mf);
   virtual bool SetGeneratorToolset(std::string const& ts, cmMakefile* mf);
 
   virtual void GenerateBuildCommand(
@@ -44,15 +45,11 @@
     std::vector<std::string> const& makeOptions = std::vector<std::string>()
     );
 
-  virtual void AddPlatformDefinitions(cmMakefile* mf);
-
   ///! create the correct local generator
   virtual cmLocalGenerator *CreateLocalGenerator();
 
-  virtual void Generate();
-
   /**
-   * Try to determine system infomation such as shared library
+   * Try to determine system information such as shared library
    * extension, pthreads, byte order etc.
    */
   virtual void EnableLanguage(std::vector<std::string>const& languages,
@@ -62,12 +59,31 @@
   /** Is the installed VS an Express edition?  */
   bool IsExpressEdition() const { return this->ExpressEdition; }
 
-  /** Is the Microsoft Assembler enabled?  */
-  bool IsMasmEnabled() const { return this->MasmEnabled; }
+  /** Generating for Nsight Tegra VS plugin?  */
+  bool IsNsightTegra() const;
+  std::string GetNsightTegraVersion() const;
 
   /** The toolset name for the target platform.  */
   const char* GetPlatformToolset() const;
 
+  /** Return the CMAKE_SYSTEM_NAME.  */
+  std::string const& GetSystemName() const { return this->SystemName; }
+
+  /** Return the CMAKE_SYSTEM_VERSION.  */
+  std::string const& GetSystemVersion() const { return this->SystemVersion; }
+
+  /** Return true if building for WindowsCE */
+  bool TargetsWindowsCE() const
+    { return this->SystemIsWindowsCE; }
+
+  /** Return true if building for WindowsPhone */
+  bool TargetsWindowsPhone() const
+    { return this->SystemIsWindowsPhone; }
+
+  /** Return true if building for WindowsStore */
+  bool TargetsWindowsStore() const
+    { return this->SystemIsWindowsStore; }
+
   /**
    * Where does this version of Visual Studio look for macros for the
    * current user? Returns the empty string if this version of Visual
@@ -94,15 +110,31 @@
 
   virtual void FindMakeProgram(cmMakefile*);
 
+  static std::string GetInstalledNsightTegraVersion();
+
 protected:
+  virtual void Generate();
+  virtual bool InitializeSystem(cmMakefile* mf);
+  virtual bool InitializeWindowsCE(cmMakefile* mf);
+  virtual bool InitializeWindowsPhone(cmMakefile* mf);
+  virtual bool InitializeWindowsStore(cmMakefile* mf);
+  virtual std::string SelectWindowsCEToolset() const;
+  virtual std::string SelectWindowsPhoneToolset() const { return ""; }
+  virtual std::string SelectWindowsStoreToolset() const { return ""; }
+
   virtual const char* GetIDEVersion() { return "10.0"; }
 
   std::string const& GetMSBuildCommand();
 
   std::string GeneratorToolset;
   std::string DefaultPlatformToolset;
+  std::string SystemName;
+  std::string SystemVersion;
+  std::string NsightTegraVersion;
+  bool SystemIsWindowsCE;
+  bool SystemIsWindowsPhone;
+  bool SystemIsWindowsStore;
   bool ExpressEdition;
-  bool MasmEnabled;
 
   bool UseFolderProperty();
 
@@ -123,6 +155,5 @@
   virtual std::string FindMSBuildCommand();
   virtual std::string FindDevEnvCommand();
   virtual std::string GetVSMakeProgram() { return this->GetMSBuildCommand(); }
-  void AddVSPlatformToolsetDefinition(cmMakefile* mf) const;
 };
 #endif
diff --git a/Source/cmGlobalVisualStudio11Generator.cxx b/Source/cmGlobalVisualStudio11Generator.cxx
index 7033f2a..39bbdc0 100644
--- a/Source/cmGlobalVisualStudio11Generator.cxx
+++ b/Source/cmGlobalVisualStudio11Generator.cxx
@@ -43,25 +43,22 @@
     const char* p = cmVS11GenName(name, genName);
     if(!p)
       { return 0; }
-    if(strcmp(p, "") == 0)
+    if(!*p)
       {
       return new cmGlobalVisualStudio11Generator(
-        genName, "", "");
+        genName, "");
       }
-    if(strcmp(p, " Win64") == 0)
-      {
-      return new cmGlobalVisualStudio11Generator(
-        genName, "x64", "CMAKE_FORCE_WIN64");
-      }
-    if(strcmp(p, " ARM") == 0)
-      {
-      return new cmGlobalVisualStudio11Generator(
-        genName, "ARM", "");
-      }
-
     if(*p++ != ' ')
+      { return 0; }
+    if(strcmp(p, "Win64") == 0)
       {
-      return 0;
+      return new cmGlobalVisualStudio11Generator(
+        genName, "x64");
+      }
+    if(strcmp(p, "ARM") == 0)
+      {
+      return new cmGlobalVisualStudio11Generator(
+        genName, "ARM");
       }
 
     std::set<std::string> installedSDKs =
@@ -73,7 +70,7 @@
       }
 
     cmGlobalVisualStudio11Generator* ret =
-      new cmGlobalVisualStudio11Generator(name, p, NULL);
+      new cmGlobalVisualStudio11Generator(name, p);
     ret->WindowsCEVersion = "8.00";
     return ret;
     }
@@ -108,10 +105,8 @@
 
 //----------------------------------------------------------------------------
 cmGlobalVisualStudio11Generator::cmGlobalVisualStudio11Generator(
-  const std::string& name, const std::string& platformName,
-  const std::string& additionalPlatformDefinition)
-  : cmGlobalVisualStudio10Generator(name, platformName,
-                                   additionalPlatformDefinition)
+  const std::string& name, const std::string& platformName)
+  : cmGlobalVisualStudio10Generator(name, platformName)
 {
   std::string vc11Express;
   this->ExpressEdition = cmSystemTools::ReadRegistryValue(
@@ -134,6 +129,56 @@
 }
 
 //----------------------------------------------------------------------------
+bool cmGlobalVisualStudio11Generator::InitializeWindowsPhone(cmMakefile* mf)
+{
+  this->DefaultPlatformToolset = this->SelectWindowsPhoneToolset();
+  if(this->DefaultPlatformToolset.empty())
+    {
+    cmOStringStream e;
+    e << this->GetName() << " supports Windows Phone '8.0', but not '"
+      << this->SystemVersion << "'.  Check CMAKE_SYSTEM_VERSION.";
+    mf->IssueMessage(cmake::FATAL_ERROR, e.str());
+    return false;
+    }
+  return true;
+}
+
+//----------------------------------------------------------------------------
+bool cmGlobalVisualStudio11Generator::InitializeWindowsStore(cmMakefile* mf)
+{
+  this->DefaultPlatformToolset = this->SelectWindowsStoreToolset();
+  if(this->DefaultPlatformToolset.empty())
+    {
+    cmOStringStream e;
+    e << this->GetName() << " supports Windows Store '8.0', but not '"
+      << this->SystemVersion << "'.  Check CMAKE_SYSTEM_VERSION.";
+    mf->IssueMessage(cmake::FATAL_ERROR, e.str());
+    return false;
+    }
+  return true;
+}
+
+//----------------------------------------------------------------------------
+std::string cmGlobalVisualStudio11Generator::SelectWindowsPhoneToolset() const
+{
+  if(this->SystemVersion == "8.0")
+    {
+    return "v110_wp80";
+    }
+  return this->cmGlobalVisualStudio10Generator::SelectWindowsPhoneToolset();
+}
+
+//----------------------------------------------------------------------------
+std::string cmGlobalVisualStudio11Generator::SelectWindowsStoreToolset() const
+{
+  if(this->SystemVersion == "8.0")
+    {
+    return "v110";
+    }
+  return this->cmGlobalVisualStudio10Generator::SelectWindowsStoreToolset();
+}
+
+//----------------------------------------------------------------------------
 void cmGlobalVisualStudio11Generator::WriteSLNHeader(std::ostream& fout)
 {
   fout << "Microsoft Visual Studio Solution File, Format Version 12.00\n";
@@ -152,7 +197,6 @@
 {
   cmLocalVisualStudio10Generator* lg =
     new cmLocalVisualStudio10Generator(cmLocalVisualStudioGenerator::VS11);
-  lg->SetPlatformName(this->GetPlatformName());
   lg->SetGlobalGenerator(this);
   return lg;
 }
@@ -198,3 +242,17 @@
 
   return ret;
 }
+
+//----------------------------------------------------------------------------
+bool
+cmGlobalVisualStudio11Generator::NeedsDeploy(cmTarget::TargetType type) const
+{
+  if((type == cmTarget::EXECUTABLE ||
+      type == cmTarget::SHARED_LIBRARY) &&
+     (this->SystemIsWindowsPhone ||
+      this->SystemIsWindowsStore))
+    {
+    return true;
+    }
+  return cmGlobalVisualStudio10Generator::NeedsDeploy(type);
+}
diff --git a/Source/cmGlobalVisualStudio11Generator.h b/Source/cmGlobalVisualStudio11Generator.h
index 48ea489..bbd935c 100644
--- a/Source/cmGlobalVisualStudio11Generator.h
+++ b/Source/cmGlobalVisualStudio11Generator.h
@@ -21,8 +21,7 @@
 {
 public:
   cmGlobalVisualStudio11Generator(const std::string& name,
-    const std::string& platformName,
-    const std::string& additionalPlatformDefinition);
+    const std::string& platformName);
   static cmGlobalGeneratorFactory* NewFactory();
 
   virtual bool MatchesGeneratorName(const std::string& name) const;
@@ -35,9 +34,16 @@
   /** TODO: VS 11 user macro support. */
   virtual std::string GetUserMacrosDirectory() { return ""; }
 protected:
+  virtual bool InitializeWindowsPhone(cmMakefile* mf);
+  virtual bool InitializeWindowsStore(cmMakefile* mf);
+  virtual std::string SelectWindowsPhoneToolset() const;
+  virtual std::string SelectWindowsStoreToolset() const;
   virtual const char* GetIDEVersion() { return "11.0"; }
   bool UseFolderProperty();
   static std::set<std::string> GetInstalledWindowsCESDKs();
+
+  /** Return true if the configuration needs to be deployed */
+  virtual bool NeedsDeploy(cmTarget::TargetType type) const;
 private:
   class Factory;
   friend class Factory;
diff --git a/Source/cmGlobalVisualStudio12Generator.cxx b/Source/cmGlobalVisualStudio12Generator.cxx
index 40f8b05..29ecfe0 100644
--- a/Source/cmGlobalVisualStudio12Generator.cxx
+++ b/Source/cmGlobalVisualStudio12Generator.cxx
@@ -43,20 +43,22 @@
     const char* p = cmVS12GenName(name, genName);
     if(!p)
       { return 0; }
-    if(strcmp(p, "") == 0)
+    if(!*p)
       {
       return new cmGlobalVisualStudio12Generator(
-        genName, "", "");
+        genName, "");
       }
-    if(strcmp(p, " Win64") == 0)
+    if(*p++ != ' ')
+      { return 0; }
+    if(strcmp(p, "Win64") == 0)
       {
       return new cmGlobalVisualStudio12Generator(
-        genName, "x64", "CMAKE_FORCE_WIN64");
+        genName, "x64");
       }
-    if(strcmp(p, " ARM") == 0)
+    if(strcmp(p, "ARM") == 0)
       {
       return new cmGlobalVisualStudio12Generator(
-        genName, "ARM", "");
+        genName, "ARM");
       }
     return 0;
     }
@@ -83,10 +85,8 @@
 
 //----------------------------------------------------------------------------
 cmGlobalVisualStudio12Generator::cmGlobalVisualStudio12Generator(
-  const std::string& name, const std::string& platformName,
-  const std::string& additionalPlatformDefinition)
-  : cmGlobalVisualStudio11Generator(name, platformName,
-                                   additionalPlatformDefinition)
+  const std::string& name, const std::string& platformName)
+  : cmGlobalVisualStudio11Generator(name, platformName)
 {
   std::string vc12Express;
   this->ExpressEdition = cmSystemTools::ReadRegistryValue(
@@ -109,6 +109,56 @@
 }
 
 //----------------------------------------------------------------------------
+bool cmGlobalVisualStudio12Generator::InitializeWindowsPhone(cmMakefile* mf)
+{
+  this->DefaultPlatformToolset = this->SelectWindowsPhoneToolset();
+  if(this->DefaultPlatformToolset.empty())
+    {
+    cmOStringStream e;
+    e << this->GetName() << " supports Windows Phone '8.0' and '8.1', "
+      "but not '" << this->SystemVersion << "'.  Check CMAKE_SYSTEM_VERSION.";
+    mf->IssueMessage(cmake::FATAL_ERROR, e.str());
+    return false;
+    }
+  return true;
+}
+
+//----------------------------------------------------------------------------
+bool cmGlobalVisualStudio12Generator::InitializeWindowsStore(cmMakefile* mf)
+{
+  this->DefaultPlatformToolset = this->SelectWindowsStoreToolset();
+  if(this->DefaultPlatformToolset.empty())
+    {
+    cmOStringStream e;
+    e << this->GetName() << " supports Windows Store '8.0' and '8.1', "
+      "but not '" << this->SystemVersion << "'.  Check CMAKE_SYSTEM_VERSION.";
+    mf->IssueMessage(cmake::FATAL_ERROR, e.str());
+    return false;
+    }
+  return true;
+}
+
+//----------------------------------------------------------------------------
+std::string cmGlobalVisualStudio12Generator::SelectWindowsPhoneToolset() const
+{
+  if(this->SystemVersion == "8.1")
+    {
+    return "v120_wp81";
+    }
+  return this->cmGlobalVisualStudio11Generator::SelectWindowsPhoneToolset();
+}
+
+//----------------------------------------------------------------------------
+std::string cmGlobalVisualStudio12Generator::SelectWindowsStoreToolset() const
+{
+  if(this->SystemVersion == "8.1")
+    {
+    return "v120";
+    }
+  return this->cmGlobalVisualStudio11Generator::SelectWindowsStoreToolset();
+}
+
+//----------------------------------------------------------------------------
 void cmGlobalVisualStudio12Generator::WriteSLNHeader(std::ostream& fout)
 {
   fout << "Microsoft Visual Studio Solution File, Format Version 12.00\n";
@@ -127,7 +177,6 @@
 {
   cmLocalVisualStudio10Generator* lg =
     new cmLocalVisualStudio10Generator(cmLocalVisualStudioGenerator::VS12);
-  lg->SetPlatformName(this->GetPlatformName());
   lg->SetGlobalGenerator(this);
   return lg;
 }
diff --git a/Source/cmGlobalVisualStudio12Generator.h b/Source/cmGlobalVisualStudio12Generator.h
index 4557f28..ec85f10 100644
--- a/Source/cmGlobalVisualStudio12Generator.h
+++ b/Source/cmGlobalVisualStudio12Generator.h
@@ -21,8 +21,7 @@
 {
 public:
   cmGlobalVisualStudio12Generator(const std::string& name,
-    const std::string& platformName,
-    const std::string& additionalPlatformDefinition);
+    const std::string& platformName);
   static cmGlobalGeneratorFactory* NewFactory();
 
   virtual bool MatchesGeneratorName(const std::string& name) const;
@@ -40,6 +39,10 @@
   //version number
   virtual const char* GetToolsVersion() { return "12.0"; }
 protected:
+  virtual bool InitializeWindowsPhone(cmMakefile* mf);
+  virtual bool InitializeWindowsStore(cmMakefile* mf);
+  virtual std::string SelectWindowsPhoneToolset() const;
+  virtual std::string SelectWindowsStoreToolset() const;
   virtual const char* GetIDEVersion() { return "12.0"; }
 private:
   class Factory;
diff --git a/Source/cmGlobalVisualStudio14Generator.cxx b/Source/cmGlobalVisualStudio14Generator.cxx
new file mode 100644
index 0000000..d001f93
--- /dev/null
+++ b/Source/cmGlobalVisualStudio14Generator.cxx
@@ -0,0 +1,113 @@
+/*============================================================================
+  CMake - Cross Platform Makefile Generator
+  Copyright 2000-2014 Kitware, Inc., Insight Software Consortium
+
+  Distributed under the OSI-approved BSD License (the "License");
+  see accompanying file Copyright.txt for details.
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the License for more information.
+============================================================================*/
+#include "cmGlobalVisualStudio14Generator.h"
+#include "cmLocalVisualStudio10Generator.h"
+#include "cmMakefile.h"
+
+static const char vs14generatorName[] = "Visual Studio 14";
+
+class cmGlobalVisualStudio14Generator::Factory
+  : public cmGlobalGeneratorFactory
+{
+public:
+  virtual cmGlobalGenerator* CreateGlobalGenerator(
+    const std::string& genName) const
+    {
+    if(strncmp(genName.c_str(), vs14generatorName,
+               sizeof(vs14generatorName) - 1) != 0)
+      {
+      return 0;
+      }
+    const char* p = genName.c_str() + sizeof(vs14generatorName) - 1;
+    if(!*p)
+      {
+      return new cmGlobalVisualStudio14Generator(
+        genName, "");
+      }
+    if(*p++ != ' ')
+      { return 0; }
+    if(strcmp(p, "Win64") == 0)
+      {
+      return new cmGlobalVisualStudio14Generator(
+        genName, "x64");
+      }
+    if(strcmp(p, "ARM") == 0)
+      {
+      return new cmGlobalVisualStudio14Generator(
+        genName, "ARM");
+      }
+    return 0;
+    }
+
+  virtual void GetDocumentation(cmDocumentationEntry& entry) const
+    {
+    entry.Name = vs14generatorName;
+    entry.Brief = "Generates Visual Studio 14 project files.";
+    }
+
+  virtual void GetGenerators(std::vector<std::string>& names) const
+    {
+    names.push_back(vs14generatorName);
+    names.push_back(vs14generatorName + std::string(" ARM"));
+    names.push_back(vs14generatorName + std::string(" Win64"));
+    }
+};
+
+//----------------------------------------------------------------------------
+cmGlobalGeneratorFactory* cmGlobalVisualStudio14Generator::NewFactory()
+{
+  return new Factory;
+}
+
+//----------------------------------------------------------------------------
+cmGlobalVisualStudio14Generator::cmGlobalVisualStudio14Generator(
+  const std::string& name, const std::string& platformName)
+  : cmGlobalVisualStudio12Generator(name, platformName)
+{
+  std::string vc14Express;
+  this->ExpressEdition = cmSystemTools::ReadRegistryValue(
+    "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VCExpress\\14.0\\Setup\\VC;"
+    "ProductDir", vc14Express, cmSystemTools::KeyWOW64_32);
+  this->DefaultPlatformToolset = "v140";
+}
+
+//----------------------------------------------------------------------------
+bool
+cmGlobalVisualStudio14Generator::MatchesGeneratorName(
+                                                const std::string& name) const
+{
+  return name == this->GetName();
+}
+
+//----------------------------------------------------------------------------
+void cmGlobalVisualStudio14Generator::WriteSLNHeader(std::ostream& fout)
+{
+  // Visual Studio 14 writes .sln format 12.00
+  fout << "Microsoft Visual Studio Solution File, Format Version 12.00\n";
+  if (this->ExpressEdition)
+    {
+    fout << "# Visual Studio Express 14 for Windows Desktop\n";
+    }
+  else
+    {
+    fout << "# Visual Studio 14\n";
+    }
+}
+
+//----------------------------------------------------------------------------
+cmLocalGenerator *cmGlobalVisualStudio14Generator::CreateLocalGenerator()
+{
+  cmLocalVisualStudio10Generator* lg =
+    new cmLocalVisualStudio10Generator(cmLocalVisualStudioGenerator::VS14);
+  lg->SetGlobalGenerator(this);
+  return lg;
+}
diff --git a/Source/cmGlobalVisualStudio14Generator.h b/Source/cmGlobalVisualStudio14Generator.h
new file mode 100644
index 0000000..3fd60a0
--- /dev/null
+++ b/Source/cmGlobalVisualStudio14Generator.h
@@ -0,0 +1,43 @@
+/*============================================================================
+  CMake - Cross Platform Makefile Generator
+  Copyright 2000-2014 Kitware, Inc., Insight Software Consortium
+
+  Distributed under the OSI-approved BSD License (the "License");
+  see accompanying file Copyright.txt for details.
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the License for more information.
+============================================================================*/
+#ifndef cmGlobalVisualStudio14Generator_h
+#define cmGlobalVisualStudio14Generator_h
+
+#include "cmGlobalVisualStudio12Generator.h"
+
+
+/** \class cmGlobalVisualStudio14Generator  */
+class cmGlobalVisualStudio14Generator:
+  public cmGlobalVisualStudio12Generator
+{
+public:
+  cmGlobalVisualStudio14Generator(const std::string& name,
+    const std::string& platformName);
+  static cmGlobalGeneratorFactory* NewFactory();
+
+  virtual bool MatchesGeneratorName(const std::string& name) const;
+
+  virtual void WriteSLNHeader(std::ostream& fout);
+
+  ///! create the correct local generator
+  virtual cmLocalGenerator *CreateLocalGenerator();
+
+  /** TODO: VS 14 user macro support. */
+  virtual std::string GetUserMacrosDirectory() { return ""; }
+
+  virtual const char* GetToolsVersion() { return "14.0"; }
+protected:
+  virtual const char* GetIDEVersion() { return "14.0"; }
+private:
+  class Factory;
+};
+#endif
diff --git a/Source/cmGlobalVisualStudio6Generator.cxx b/Source/cmGlobalVisualStudio6Generator.cxx
index 7397bbb..455a7a2 100644
--- a/Source/cmGlobalVisualStudio6Generator.cxx
+++ b/Source/cmGlobalVisualStudio6Generator.cxx
@@ -41,7 +41,6 @@
                  cmMakefile *mf,
                  bool optional)
 {
-  cmGlobalVisualStudioGenerator::AddPlatformDefinitions(mf);
   mf->AddDefinition("CMAKE_GENERATOR_RC", "rc");
   mf->AddDefinition("CMAKE_GENERATOR_NO_COMPILER_ENV", "1");
   this->GenerateConfigurations(mf);
diff --git a/Source/cmGlobalVisualStudio6Generator.h b/Source/cmGlobalVisualStudio6Generator.h
index 2797e11..58efb25 100644
--- a/Source/cmGlobalVisualStudio6Generator.h
+++ b/Source/cmGlobalVisualStudio6Generator.h
@@ -42,7 +42,7 @@
   virtual cmLocalGenerator *CreateLocalGenerator();
 
   /**
-   * Try to determine system infomation such as shared library
+   * Try to determine system information such as shared library
    * extension, pthreads, byte order etc.
    */
   virtual void EnableLanguage(std::vector<std::string>const& languages,
@@ -64,13 +64,6 @@
     );
 
   /**
-   * Generate the all required files for building this project/tree. This
-   * basically creates a series of LocalGenerators for each directory and
-   * requests that they Generate.
-   */
-  virtual void Generate();
-
-  /**
    * Generate the DSW workspace file.
    */
   virtual void OutputDSWFile();
@@ -91,7 +84,10 @@
 
   virtual void FindMakeProgram(cmMakefile*);
 
+  virtual bool IsForVS6() const { return true; }
+
 protected:
+  virtual void Generate();
   virtual const char* GetIDEVersion() { return "6.0"; }
 private:
   virtual std::string GetVSMakeProgram() { return this->GetMSDevCommand(); }
diff --git a/Source/cmGlobalVisualStudio71Generator.cxx b/Source/cmGlobalVisualStudio71Generator.cxx
index 4bea5ac..a67a649 100644
--- a/Source/cmGlobalVisualStudio71Generator.cxx
+++ b/Source/cmGlobalVisualStudio71Generator.cxx
@@ -118,7 +118,7 @@
   fout << "\tGlobalSection(" << this->ProjectConfigurationSectionName
        << ") = postSolution\n";
   // Write out the configurations for all the targets in the project
-  this->WriteTargetConfigurations(fout, root, orderedProjectTargets);
+  this->WriteTargetConfigurations(fout, orderedProjectTargets);
   fout << "\tEndGlobalSection\n";
 
   if (useFolderProperty)
diff --git a/Source/cmGlobalVisualStudio7Generator.cxx b/Source/cmGlobalVisualStudio7Generator.cxx
index b581147..401e475 100644
--- a/Source/cmGlobalVisualStudio7Generator.cxx
+++ b/Source/cmGlobalVisualStudio7Generator.cxx
@@ -23,14 +23,15 @@
 {
   this->IntelProjectVersion = 0;
   this->DevEnvCommandInitialized = false;
+  this->MasmEnabled = false;
 
   if (platformName.empty())
     {
-    this->PlatformName = "Win32";
+    this->DefaultPlatformName = "Win32";
     }
   else
     {
-    this->PlatformName = platformName;
+    this->DefaultPlatformName = platformName;
     }
 }
 
@@ -80,7 +81,6 @@
 {
   mf->AddDefinition("CMAKE_GENERATOR_RC", "rc");
   mf->AddDefinition("CMAKE_GENERATOR_NO_COMPILER_ENV", "1");
-  this->AddPlatformDefinitions(mf);
   if(!mf->GetDefinition("CMAKE_CONFIGURATION_TYPES"))
     {
     mf->AddCacheDefinition(
@@ -260,12 +260,38 @@
 }
 
 //----------------------------------------------------------------------------
-void cmGlobalVisualStudio7Generator::AddPlatformDefinitions(cmMakefile* mf)
+std::string const& cmGlobalVisualStudio7Generator::GetPlatformName() const
 {
-  cmGlobalVisualStudioGenerator::AddPlatformDefinitions(mf);
-  mf->AddDefinition("CMAKE_VS_PLATFORM_NAME", this->GetPlatformName().c_str());
+  if(!this->GeneratorPlatform.empty())
+    {
+    return this->GeneratorPlatform;
+    }
+  return this->DefaultPlatformName;
+}
+
+//----------------------------------------------------------------------------
+bool cmGlobalVisualStudio7Generator::SetSystemName(std::string const& s,
+                                                   cmMakefile* mf)
+{
   mf->AddDefinition("CMAKE_VS_INTEL_Fortran_PROJECT_VERSION",
                     this->GetIntelProjectVersion());
+  return this->cmGlobalVisualStudioGenerator::SetSystemName(s, mf);
+}
+
+//----------------------------------------------------------------------------
+bool cmGlobalVisualStudio7Generator::SetGeneratorPlatform(std::string const& p,
+                                                          cmMakefile* mf)
+{
+  if(this->GetPlatformName() == "x64")
+    {
+    mf->AddDefinition("CMAKE_FORCE_WIN64", "TRUE");
+    }
+  else if(this->GetPlatformName() == "Itanium")
+    {
+    mf->AddDefinition("CMAKE_FORCE_IA64", "TRUE");
+    }
+  mf->AddDefinition("CMAKE_VS_PLATFORM_NAME", this->GetPlatformName().c_str());
+  return this->cmGlobalVisualStudioGenerator::SetGeneratorPlatform(p, mf);
 }
 
 void cmGlobalVisualStudio7Generator::GenerateConfigurations(cmMakefile* mf)
@@ -366,7 +392,6 @@
 
 void cmGlobalVisualStudio7Generator::WriteTargetConfigurations(
   std::ostream& fout,
-  cmLocalGenerator* root,
   OrderedTargetDependSet const& projectTargets)
 {
   // loop over again and write out configurations for each target
@@ -392,8 +417,7 @@
     else
       {
       const std::set<std::string>& configsPartOfDefaultBuild =
-        this->IsPartOfDefaultBuild(root->GetMakefile()->GetProjectName(),
-                                   target);
+        this->IsPartOfDefaultBuild(projectTargets, target);
       const char *vcprojName =
         target->GetProperty("GENERATOR_FILE_NAME");
       if (vcprojName)
@@ -579,7 +603,7 @@
 
   // Write out the configurations for all the targets in the project
   fout << "\tGlobalSection(ProjectConfiguration) = postSolution\n";
-  this->WriteTargetConfigurations(fout, root, orderedProjectTargets);
+  this->WriteTargetConfigurations(fout, orderedProjectTargets);
   fout << "\tEndGlobalSection\n";
 
   // Write out global sections
@@ -767,7 +791,6 @@
                                const char* typeGuid,
                                const std::set<std::string>&)
 {
-  std::string d = cmSystemTools::ConvertToOutputPath(location);
   fout << "Project("
        << "\"{"
        << (typeGuid ? typeGuid : this->ExternalProjectType(location))
@@ -981,8 +1004,7 @@
 
 std::set<std::string>
 cmGlobalVisualStudio7Generator::IsPartOfDefaultBuild(
-                                                    const std::string& project,
-                                                    cmTarget const* target)
+  OrderedTargetDependSet const& projectTargets, cmTarget const* target)
 {
   std::set<std::string> activeConfigs;
   // if it is a utilitiy target then only make it part of the
@@ -992,7 +1014,7 @@
     {
     return activeConfigs;
     }
-  if(type == cmTarget::UTILITY && !this->IsDependedOn(project, target))
+  if(type == cmTarget::UTILITY && !this->IsDependedOn(projectTargets, target))
     {
     return activeConfigs;
     }
@@ -1010,6 +1032,24 @@
   return activeConfigs;
 }
 
+bool
+cmGlobalVisualStudio7Generator
+::IsDependedOn(OrderedTargetDependSet const& projectTargets,
+               cmTarget const* targetIn)
+{
+  for (OrderedTargetDependSet::const_iterator l = projectTargets.begin();
+       l != projectTargets.end(); ++l)
+    {
+    cmTarget const& target = **l;
+    TargetDependSet const& tgtdeps = this->GetTargetDirectDepends(target);
+    if(tgtdeps.count(targetIn))
+      {
+      return true;
+      }
+    }
+  return false;
+}
+
 //----------------------------------------------------------------------------
 static cmVS7FlagTable cmVS7ExtraFlagTable[] =
 {
diff --git a/Source/cmGlobalVisualStudio7Generator.h b/Source/cmGlobalVisualStudio7Generator.h
index 1dc709d..201a6a6 100644
--- a/Source/cmGlobalVisualStudio7Generator.h
+++ b/Source/cmGlobalVisualStudio7Generator.h
@@ -39,18 +39,20 @@
   static std::string GetActualName() {return "Visual Studio 7";}
 
   ///! Get the name for the platform.
-  const std::string& GetPlatformName() const { return this->PlatformName; }
+  std::string const& GetPlatformName() const;
 
   ///! Create a local generator appropriate to this Global Generator
   virtual cmLocalGenerator *CreateLocalGenerator();
 
-  virtual void AddPlatformDefinitions(cmMakefile* mf);
+  virtual bool SetSystemName(std::string const& s, cmMakefile* mf);
+
+  virtual bool SetGeneratorPlatform(std::string const& p, cmMakefile* mf);
 
   /** Get the documentation entry for this generator.  */
   static void GetDocumentation(cmDocumentationEntry& entry);
 
   /**
-   * Try to determine system infomation such as shared library
+   * Try to determine system information such as shared library
    * extension, pthreads, byte order etc.
    */
   virtual void EnableLanguage(std::vector<std::string>const& languages,
@@ -72,13 +74,6 @@
     );
 
   /**
-   * Generate the all required files for building this project/tree. This
-   * basically creates a series of LocalGenerators for each directory and
-   * requests that they Generate.
-   */
-  virtual void Generate();
-
-  /**
    * Generate the DSW workspace file.
    */
   virtual void OutputSLNFile();
@@ -109,10 +104,14 @@
 
   virtual void FindMakeProgram(cmMakefile*);
 
+  /** Is the Microsoft Assembler enabled?  */
+  bool IsMasmEnabled() const { return this->MasmEnabled; }
+
   // Encoding for Visual Studio files
   virtual std::string Encoding();
 
 protected:
+  virtual void Generate();
   virtual const char* GetIDEVersion() { return "7.0"; }
 
   std::string const& GetDevEnvCommand();
@@ -150,7 +149,6 @@
     OrderedTargetDependSet const& projectTargets);
   virtual void WriteTargetConfigurations(
     std::ostream& fout,
-    cmLocalGenerator* root,
     OrderedTargetDependSet const& projectTargets);
 
   void GenerateConfigurations(cmMakefile* mf);
@@ -164,8 +162,11 @@
 
   std::string ConvertToSolutionPath(const char* path);
 
-  std::set<std::string> IsPartOfDefaultBuild(const std::string& project,
-                                             cmTarget const* target);
+  std::set<std::string>
+    IsPartOfDefaultBuild(OrderedTargetDependSet const& projectTargets,
+                         cmTarget const* target);
+  bool IsDependedOn(OrderedTargetDependSet const& projectTargets,
+                    cmTarget const* target);
   std::vector<std::string> Configurations;
   std::map<std::string, std::string> GUIDMap;
 
@@ -176,7 +177,9 @@
   // Set during OutputSLNFile with the name of the current project.
   // There is one SLN file per project.
   std::string CurrentProject;
-  std::string PlatformName;
+  std::string GeneratorPlatform;
+  std::string DefaultPlatformName;
+  bool MasmEnabled;
 
 private:
   char* IntelProjectVersion;
diff --git a/Source/cmGlobalVisualStudio8Generator.cxx b/Source/cmGlobalVisualStudio8Generator.cxx
index e6672a8..745515b 100644
--- a/Source/cmGlobalVisualStudio8Generator.cxx
+++ b/Source/cmGlobalVisualStudio8Generator.cxx
@@ -36,7 +36,7 @@
     if(p[0] == '\0')
       {
       return new cmGlobalVisualStudio8Generator(
-        name, "", "");
+        name, "");
       }
 
     if(p[0] != ' ')
@@ -49,7 +49,7 @@
     if(!strcmp(p, "Win64"))
       {
       return new cmGlobalVisualStudio8Generator(
-        name, "x64", "CMAKE_FORCE_WIN64");
+        name, "x64");
       }
 
     cmVisualStudioWCEPlatformParser parser(p);
@@ -60,7 +60,7 @@
       }
 
     cmGlobalVisualStudio8Generator* ret = new cmGlobalVisualStudio8Generator(
-      name, p, "");
+      name, p);
     ret->WindowsCEVersion = parser.GetOSVersion();
     return ret;
   }
@@ -93,17 +93,11 @@
 
 //----------------------------------------------------------------------------
 cmGlobalVisualStudio8Generator::cmGlobalVisualStudio8Generator(
-  const std::string& name, const std::string& platformName,
-  const std::string& additionalPlatformDefinition)
+  const std::string& name, const std::string& platformName)
   : cmGlobalVisualStudio71Generator(platformName)
 {
   this->ProjectConfigurationSectionName = "ProjectConfigurationPlatforms";
   this->Name = name;
-
-  if (!additionalPlatformDefinition.empty())
-    {
-    this->AdditionalPlatformDefinition = additionalPlatformDefinition;
-    }
 }
 
 //----------------------------------------------------------------------------
@@ -132,17 +126,31 @@
 {
   cmLocalVisualStudio7Generator *lg =
     new cmLocalVisualStudio7Generator(cmLocalVisualStudioGenerator::VS8);
-  lg->SetPlatformName(this->GetPlatformName());
   lg->SetExtraFlagTable(this->GetExtraFlagTableVS8());
   lg->SetGlobalGenerator(this);
   return lg;
 }
 
 //----------------------------------------------------------------------------
+void cmGlobalVisualStudio8Generator
+::EnableLanguage(std::vector<std::string>const &  lang,
+                 cmMakefile *mf, bool optional)
+{
+  for(std::vector<std::string>::const_iterator it = lang.begin();
+      it != lang.end(); ++it)
+    {
+    if(*it == "ASM_MASM")
+      {
+      this->MasmEnabled = true;
+      }
+    }
+  this->AddPlatformDefinitions(mf);
+  cmGlobalVisualStudio7Generator::EnableLanguage(lang, mf, optional);
+}
+
+//----------------------------------------------------------------------------
 void cmGlobalVisualStudio8Generator::AddPlatformDefinitions(cmMakefile* mf)
 {
-  cmGlobalVisualStudio71Generator::AddPlatformDefinitions(mf);
-
   if(this->TargetsWindowsCE())
   {
     mf->AddDefinition("CMAKE_VS_WINCE_VERSION",
@@ -151,6 +159,21 @@
 }
 
 //----------------------------------------------------------------------------
+bool cmGlobalVisualStudio8Generator::SetGeneratorPlatform(std::string const& p,
+                                                          cmMakefile* mf)
+{
+  if(this->DefaultPlatformName == "Win32")
+    {
+    this->GeneratorPlatform = p;
+    return this->cmGlobalVisualStudio7Generator::SetGeneratorPlatform("", mf);
+    }
+  else
+    {
+    return this->cmGlobalVisualStudio7Generator::SetGeneratorPlatform(p, mf);
+    }
+}
+
+//----------------------------------------------------------------------------
 // ouput standard header for dsw file
 void cmGlobalVisualStudio8Generator::WriteSLNHeader(std::ostream& fout)
 {
@@ -398,9 +421,7 @@
                platformMapping : this->GetPlatformName())
            << "\n";
       }
-    bool needsDeploy = (type == cmTarget::EXECUTABLE ||
-                        type == cmTarget::SHARED_LIBRARY);
-    if(this->TargetsWindowsCE() && needsDeploy)
+    if(this->NeedsDeploy(type))
       {
       fout << "\t\t{" << guid << "}." << *i
            << "|" << this->GetPlatformName() << ".Deploy.0 = " << *i << "|"
@@ -412,6 +433,15 @@
 }
 
 //----------------------------------------------------------------------------
+bool
+cmGlobalVisualStudio8Generator::NeedsDeploy(cmTarget::TargetType type) const
+{
+  bool needsDeploy = (type == cmTarget::EXECUTABLE ||
+                      type == cmTarget::SHARED_LIBRARY);
+  return this->TargetsWindowsCE() && needsDeploy;
+}
+
+//----------------------------------------------------------------------------
 bool cmGlobalVisualStudio8Generator::ComputeTargetDepends()
 {
   // Skip over the cmGlobalVisualStudioGenerator implementation!
diff --git a/Source/cmGlobalVisualStudio8Generator.h b/Source/cmGlobalVisualStudio8Generator.h
index 2459c05..4b41ed7 100644
--- a/Source/cmGlobalVisualStudio8Generator.h
+++ b/Source/cmGlobalVisualStudio8Generator.h
@@ -24,8 +24,7 @@
 {
 public:
   cmGlobalVisualStudio8Generator(const std::string& name,
-    const std::string& platformName,
-    const std::string& additionalPlatformDefinition);
+    const std::string& platformName);
   static cmGlobalGeneratorFactory* NewFactory();
 
   ///! Get the name for the generator.
@@ -37,14 +36,17 @@
   ///! Create a local generator appropriate to this Global Generator
   virtual cmLocalGenerator *CreateLocalGenerator();
 
+  virtual void EnableLanguage(std::vector<std::string>const& languages,
+                              cmMakefile *, bool optional);
   virtual void AddPlatformDefinitions(cmMakefile* mf);
 
+  virtual bool SetGeneratorPlatform(std::string const& p, cmMakefile* mf);
+
   /**
    * Override Configure and Generate to add the build-system check
    * target.
    */
   virtual void Configure();
-  virtual void Generate();
 
   /**
    * Where does this version of Visual Studio look for macros for the
@@ -68,6 +70,7 @@
     return !this->WindowsCEVersion.empty(); }
 
 protected:
+  virtual void Generate();
   virtual const char* GetIDEVersion() { return "8.0"; }
 
   virtual std::string FindDevEnvCommand();
@@ -76,6 +79,9 @@
 
   bool AddCheckTarget();
 
+  /** Return true if the configuration needs to be deployed */
+  virtual bool NeedsDeploy(cmTarget::TargetType type) const;
+
   static cmIDEFlagTable const* GetExtraFlagTableVS8();
   virtual void WriteSLNHeader(std::ostream& fout);
   virtual void WriteSolutionConfigurations(std::ostream& fout);
diff --git a/Source/cmGlobalVisualStudio9Generator.cxx b/Source/cmGlobalVisualStudio9Generator.cxx
index c0051c7..1d73b5c 100644
--- a/Source/cmGlobalVisualStudio9Generator.cxx
+++ b/Source/cmGlobalVisualStudio9Generator.cxx
@@ -34,7 +34,7 @@
     if(p[0] == '\0')
       {
       return new cmGlobalVisualStudio9Generator(
-        name, "", "");
+        name, "");
       }
 
     if(p[0] != ' ')
@@ -47,13 +47,13 @@
     if(!strcmp(p, "IA64"))
       {
       return new cmGlobalVisualStudio9Generator(
-        name, "Itanium", "CMAKE_FORCE_IA64");
+        name, "Itanium");
       }
 
     if(!strcmp(p, "Win64"))
       {
       return new cmGlobalVisualStudio9Generator(
-        name, "x64", "CMAKE_FORCE_WIN64");
+        name, "x64");
       }
 
     cmVisualStudioWCEPlatformParser parser(p);
@@ -64,7 +64,7 @@
       }
 
     cmGlobalVisualStudio9Generator* ret = new cmGlobalVisualStudio9Generator(
-      name, p, NULL);
+      name, p);
     ret->WindowsCEVersion = parser.GetOSVersion();
     return ret;
   }
@@ -98,10 +98,8 @@
 
 //----------------------------------------------------------------------------
 cmGlobalVisualStudio9Generator::cmGlobalVisualStudio9Generator(
-  const std::string& name, const std::string& platformName,
-  const std::string& additionalPlatformDefinition)
-  : cmGlobalVisualStudio8Generator(name, platformName,
-                                   additionalPlatformDefinition)
+  const std::string& name, const std::string& platformName)
+  : cmGlobalVisualStudio8Generator(name, platformName)
 {
 }
 
@@ -117,21 +115,12 @@
 {
   cmLocalVisualStudio7Generator *lg
     = new cmLocalVisualStudio7Generator(cmLocalVisualStudioGenerator::VS9);
-  lg->SetPlatformName(this->GetPlatformName());
   lg->SetExtraFlagTable(this->GetExtraFlagTableVS8());
   lg->SetGlobalGenerator(this);
   return lg;
 }
 
 //----------------------------------------------------------------------------
-void cmGlobalVisualStudio9Generator
-::EnableLanguage(std::vector<std::string>const &  lang,
-                 cmMakefile *mf, bool optional)
-{
-  cmGlobalVisualStudio8Generator::EnableLanguage(lang, mf, optional);
-}
-
-//----------------------------------------------------------------------------
 std::string cmGlobalVisualStudio9Generator::GetUserMacrosDirectory()
 {
   std::string base;
diff --git a/Source/cmGlobalVisualStudio9Generator.h b/Source/cmGlobalVisualStudio9Generator.h
index fb87bbe..0a191cd 100644
--- a/Source/cmGlobalVisualStudio9Generator.h
+++ b/Source/cmGlobalVisualStudio9Generator.h
@@ -25,19 +25,16 @@
 {
 public:
   cmGlobalVisualStudio9Generator(const std::string& name,
-    const std::string& platformName,
-    const std::string& additionalPlatformDefinition);
+    const std::string& platformName);
   static cmGlobalGeneratorFactory* NewFactory();
 
   ///! create the correct local generator
   virtual cmLocalGenerator *CreateLocalGenerator();
 
   /**
-   * Try to determine system infomation such as shared library
+   * Try to determine system information such as shared library
    * extension, pthreads, byte order etc.
    */
-  virtual void EnableLanguage(std::vector<std::string>const& languages,
-                              cmMakefile *, bool optional);
   virtual void WriteSLNHeader(std::ostream& fout);
 
   /**
diff --git a/Source/cmGlobalVisualStudioGenerator.cxx b/Source/cmGlobalVisualStudioGenerator.cxx
index c5a0e29..2dab23c 100644
--- a/Source/cmGlobalVisualStudioGenerator.cxx
+++ b/Source/cmGlobalVisualStudioGenerator.cxx
@@ -23,7 +23,6 @@
 //----------------------------------------------------------------------------
 cmGlobalVisualStudioGenerator::cmGlobalVisualStudioGenerator()
 {
-  this->AdditionalPlatformDefinition = "";
 }
 
 //----------------------------------------------------------------------------
@@ -478,15 +477,6 @@
 }
 
 //----------------------------------------------------------------------------
-void cmGlobalVisualStudioGenerator::AddPlatformDefinitions(cmMakefile* mf)
-{
-  if(!this->AdditionalPlatformDefinition.empty())
-    {
-    mf->AddDefinition(this->AdditionalPlatformDefinition, "TRUE");
-    }
-}
-
-//----------------------------------------------------------------------------
 std::string
 cmGlobalVisualStudioGenerator::GetUtilityDepend(cmTarget const* target)
 {
diff --git a/Source/cmGlobalVisualStudioGenerator.h b/Source/cmGlobalVisualStudioGenerator.h
index 1ab8990..356f4d4 100644
--- a/Source/cmGlobalVisualStudioGenerator.h
+++ b/Source/cmGlobalVisualStudioGenerator.h
@@ -27,11 +27,6 @@
   virtual ~cmGlobalVisualStudioGenerator();
 
   /**
-   * Basic generate implementation for all VS generators.
-   */
-  virtual void Generate();
-
-  /**
    * Configure CMake's Visual Studio macros file into the user's Visual
    * Studio macros directory.
    */
@@ -90,6 +85,8 @@
 
   void ComputeTargetObjectDirectory(cmGeneratorTarget* gt) const;
 protected:
+  virtual void Generate();
+
   // Does this VS version link targets to each other if there are
   // dependencies in the SLN file?  This was done for VS versions
   // below 8.
@@ -97,8 +94,6 @@
 
   virtual const char* GetIDEVersion() = 0;
 
-  virtual void AddPlatformDefinitions(cmMakefile* mf);
-
   virtual bool ComputeTargetDepends();
   class VSDependSet: public std::set<std::string> {};
   class VSDependMap: public std::map<cmTarget const*, VSDependSet> {};
@@ -111,7 +106,6 @@
   std::string GetUtilityDepend(cmTarget const* target);
   typedef std::map<cmTarget const*, std::string> UtilityDependsMap;
   UtilityDependsMap UtilityDepends;
-  std::string AdditionalPlatformDefinition;
 
 private:
   virtual std::string GetVSMakeProgram() = 0;
diff --git a/Source/cmGlobalWatcomWMakeGenerator.h b/Source/cmGlobalWatcomWMakeGenerator.h
index 2057a42..0e577b5 100644
--- a/Source/cmGlobalWatcomWMakeGenerator.h
+++ b/Source/cmGlobalWatcomWMakeGenerator.h
@@ -38,7 +38,7 @@
   virtual cmLocalGenerator *CreateLocalGenerator();
 
   /**
-   * Try to determine system infomation such as shared library
+   * Try to determine system information such as shared library
    * extension, pthreads, byte order etc.
    */
   virtual void EnableLanguage(std::vector<std::string>const& languages,
diff --git a/Source/cmGlobalXCodeGenerator.cxx b/Source/cmGlobalXCodeGenerator.cxx
index 29a5955..13e6988 100644
--- a/Source/cmGlobalXCodeGenerator.cxx
+++ b/Source/cmGlobalXCodeGenerator.cxx
@@ -208,8 +208,11 @@
   if(this->XcodeVersion >= 30)
     {
     this->GeneratorToolset = ts;
-    mf->AddDefinition("CMAKE_XCODE_PLATFORM_TOOLSET",
-                      this->GeneratorToolset.c_str());
+    if(!this->GeneratorToolset.empty())
+      {
+      mf->AddDefinition("CMAKE_XCODE_PLATFORM_TOOLSET",
+                        this->GeneratorToolset.c_str());
+      }
     return true;
     }
   else
@@ -830,16 +833,14 @@
   const std::string &lang,
   cmSourceFile* sf)
 {
-  std::string fname = fullpath;
-  cmXCodeObject* fileRef = this->FileRefs[fname];
+  std::string key = GetGroupMapKeyFromPath(cmtarget, fullpath);
+  cmXCodeObject* fileRef = this->FileRefs[key];
   if(!fileRef)
     {
     fileRef = this->CreateObject(cmXCodeObject::PBXFileReference);
-    std::string comment = fname;
-    fileRef->SetComment(fname.c_str());
-    this->FileRefs[fname] = fileRef;
+    fileRef->SetComment(fullpath);
+    this->FileRefs[key] = fileRef;
     }
-  std::string key = GetGroupMapKeyFromPath(cmtarget, fullpath);
   cmXCodeObject* group = this->GroupMap[key];
   cmXCodeObject* children = group->GetObject("children");
   if (!children->HasObject(fileRef))
@@ -864,24 +865,24 @@
     }
   if(fileType.empty())
     {
+    // Compute the extension without leading '.'.
+    std::string ext = cmSystemTools::GetFilenameLastExtension(fullpath);
+    if(!ext.empty())
+      {
+      ext = ext.substr(1);
+      }
+
     // If fullpath references a directory, then we need to specify
     // lastKnownFileType as folder in order for Xcode to be able to
     // open the contents of the folder.
     // (Xcode 4.6 does not like explicitFileType=folder).
     if(cmSystemTools::FileIsDirectory(fullpath.c_str()))
       {
-      fileType = "folder";
+      fileType = (ext == "xcassets"? "folder.assetcatalog" : "folder");
       useLastKnownFileType = true;
       }
     else
       {
-      // Compute the extension without leading '.'.
-      std::string ext = cmSystemTools::GetFilenameLastExtension(fullpath);
-      if(!ext.empty())
-        {
-        ext = ext.substr(1);
-        }
-
       fileType = GetSourcecodeValueFromFileExtension(
         ext, lang, useLastKnownFileType);
       }
@@ -1255,7 +1256,7 @@
 
   // If the language is compiled as a source trust Xcode to link with it.
   cmTarget::LinkImplementation const* impl =
-    cmtarget.GetLinkImplementation("NOCONFIG", &cmtarget);
+    cmtarget.GetLinkImplementation("NOCONFIG");
   for(std::vector<std::string>::const_iterator li = impl->Languages.begin();
       li != impl->Languages.end(); ++li)
     {
@@ -2299,7 +2300,7 @@
       }
     }
 
-  buildSettings->AddAttribute("OTHER_LDFLAGS",
+  buildSettings->AddAttribute(this->GetTargetLinkFlagsVar(target),
                               this->CreateString(extraLinkOptions.c_str()));
   buildSettings->AddAttribute("OTHER_REZFLAGS",
                               this->CreateString(""));
@@ -2527,6 +2528,22 @@
 }
 
 //----------------------------------------------------------------------------
+const char*
+cmGlobalXCodeGenerator::GetTargetLinkFlagsVar(cmTarget const& cmtarget) const
+{
+  if(this->XcodeVersion >= 60 &&
+     (cmtarget.GetType() == cmTarget::STATIC_LIBRARY ||
+      cmtarget.GetType() == cmTarget::OBJECT_LIBRARY))
+    {
+    return "OTHER_LIBTOOLFLAGS";
+    }
+  else
+    {
+    return "OTHER_LDFLAGS";
+    }
+}
+
+//----------------------------------------------------------------------------
 const char* cmGlobalXCodeGenerator::GetTargetFileType(cmTarget& cmtarget)
 {
   switch(cmtarget.GetType())
@@ -2835,8 +2852,9 @@
         sep = " ";
         linkObjs += this->XCodeEscapePath(oi->c_str());
         }
-      this->AppendBuildSettingAttribute(target, "OTHER_LDFLAGS",
-                                        linkObjs.c_str(), configName);
+      this->AppendBuildSettingAttribute(
+        target, this->GetTargetLinkFlagsVar(*cmtarget),
+        linkObjs.c_str(), configName);
       }
 
     // Skip link information for object libraries.
@@ -2914,8 +2932,9 @@
         target->AddDependTarget(configName, li->Target->GetName());
         }
       }
-    this->AppendBuildSettingAttribute(target, "OTHER_LDFLAGS",
-                                      linkLibs.c_str(), configName);
+    this->AppendBuildSettingAttribute(
+      target, this->GetTargetLinkFlagsVar(*cmtarget),
+      linkLibs.c_str(), configName);
     }
     }
 }
diff --git a/Source/cmGlobalXCodeGenerator.h b/Source/cmGlobalXCodeGenerator.h
index ae23e3b..9d7b784 100644
--- a/Source/cmGlobalXCodeGenerator.h
+++ b/Source/cmGlobalXCodeGenerator.h
@@ -44,7 +44,7 @@
   virtual cmLocalGenerator *CreateLocalGenerator();
 
   /**
-   * Try to determine system infomation such as shared library
+   * Try to determine system information such as shared library
    * extension, pthreads, byte order etc.
    */
   virtual void EnableLanguage(std::vector<std::string>const& languages,
@@ -64,13 +64,6 @@
     std::vector<std::string> const& makeOptions = std::vector<std::string>()
     );
 
-  /**
-   * Generate the all required files for building this project/tree. This
-   * basically creates a series of LocalGenerators for each directory and
-   * requests that they Generate.
-   */
-  virtual void Generate();
-
   /** Append the subdirectory for the given configuration.  */
   virtual void AppendDirectoryForConfig(const std::string& prefix,
                                         const std::string& config,
@@ -91,6 +84,8 @@
 
   virtual bool SetGeneratorToolset(std::string const& ts, cmMakefile* mf);
   void AppendFlag(std::string& flags, std::string const& flag);
+protected:
+  virtual void Generate();
 private:
   cmXCodeObject* CreateOrGetPBXGroup(cmTarget& cmtarget,
                                      cmSourceGroup* sg);
@@ -139,6 +134,7 @@
                                    cmXCodeObject* buildPhases);
   void ForceLinkerLanguages();
   void ForceLinkerLanguage(cmTarget& cmtarget);
+  const char* GetTargetLinkFlagsVar(cmTarget const& cmtarget) const;
   const char* GetTargetFileType(cmTarget& cmtarget);
   const char* GetTargetProductType(cmTarget& cmtarget);
   std::string AddConfigurations(cmXCodeObject* target, cmTarget& cmtarget);
diff --git a/Source/cmIDEOptions.cxx b/Source/cmIDEOptions.cxx
index 1f3c066..0eb903d 100644
--- a/Source/cmIDEOptions.cxx
+++ b/Source/cmIDEOptions.cxx
@@ -152,18 +152,7 @@
     }
   else if(entry->special & cmIDEFlagTable::SemicolonAppendable)
     {
-    std::map<std::string,std::string>::iterator itr;
-    itr = this->FlagMap.find(entry->IDEName);
-    if(itr != this->FlagMap.end())
-      {
-      // Append to old value (if present) with semicolons;
-      itr->second += ";";
-      itr->second += new_value;
-      }
-    else
-      {
-      this->FlagMap[entry->IDEName] = new_value;
-      }
+    this->FlagMap[entry->IDEName].push_back(new_value);
     }
   else
     {
@@ -200,18 +189,47 @@
 }
 
 //----------------------------------------------------------------------------
+void cmIDEOptions::AddFlag(const char* flag,
+                           std::vector<std::string> const& value)
+{
+  this->FlagMap[flag] = value;
+}
+
+//----------------------------------------------------------------------------
+void cmIDEOptions::AppendFlag(std::string const& flag,
+                              std::string const& value)
+{
+  this->FlagMap[flag].push_back(value);
+}
+
+//----------------------------------------------------------------------------
+void cmIDEOptions::AppendFlag(std::string const& flag,
+                              std::vector<std::string> const& value)
+{
+  FlagValue& fv = this->FlagMap[flag];
+  std::copy(value.begin(), value.end(), std::back_inserter(fv));
+}
+
+//----------------------------------------------------------------------------
 void cmIDEOptions::RemoveFlag(const char* flag)
 {
   this->FlagMap.erase(flag);
 }
 
 //----------------------------------------------------------------------------
+bool cmIDEOptions::HasFlag(std::string const& flag) const
+{
+  return this->FlagMap.find(flag) != this->FlagMap.end();
+}
+
+//----------------------------------------------------------------------------
 const char* cmIDEOptions::GetFlag(const char* flag)
 {
-  std::map<std::string, std::string>::iterator i = this->FlagMap.find(flag);
-  if(i != this->FlagMap.end())
+  // This method works only for single-valued flags!
+  std::map<std::string, FlagValue>::iterator i = this->FlagMap.find(flag);
+  if(i != this->FlagMap.end() && i->second.size() == 1)
     {
-    return i->second.c_str();
+    return i->second[0].c_str();
     }
   return 0;
 }
diff --git a/Source/cmIDEOptions.h b/Source/cmIDEOptions.h
index e7749ec..7386016 100644
--- a/Source/cmIDEOptions.h
+++ b/Source/cmIDEOptions.h
@@ -29,7 +29,12 @@
   void AddDefines(const char* defines);
   void AddDefines(const std::vector<std::string> &defines);
   void AddFlag(const char* flag, const char* value);
+  void AddFlag(const char* flag, std::vector<std::string> const& value);
+  void AppendFlag(std::string const& flag, std::string const& value);
+  void AppendFlag(std::string const& flag,
+                  std::vector<std::string> const& value);
   void RemoveFlag(const char* flag);
+  bool HasFlag(std::string const& flag) const;
   const char* GetFlag(const char* flag);
 
 protected:
@@ -40,7 +45,23 @@
   // Then parse the command line flags specified in CMAKE_CXX_FLAGS
   // and CMAKE_C_FLAGS
   // and overwrite or add new values to this map
-  std::map<std::string, std::string> FlagMap;
+  class FlagValue: public std::vector<std::string>
+  {
+    typedef std::vector<std::string> derived;
+  public:
+    FlagValue& operator=(std::string const& r)
+      {
+      this->resize(1);
+      this->operator[](0) = r;
+      return *this;
+      }
+    FlagValue& operator=(std::vector<std::string> const& r)
+      {
+      this->derived::operator=(r);
+      return *this;
+      }
+  };
+  std::map<std::string, FlagValue > FlagMap;
 
   // Preprocessor definitions.
   std::vector<std::string> Defines;
diff --git a/Source/cmIfCommand.cxx b/Source/cmIfCommand.cxx
index 1141b01..f728c15 100644
--- a/Source/cmIfCommand.cxx
+++ b/Source/cmIfCommand.cxx
@@ -12,21 +12,23 @@
 #include "cmIfCommand.h"
 #include "cmStringCommand.h"
 
+#include "cmConditionEvaluator.h"
+
 #include <stdlib.h> // required for atof
 #include <list>
 #include <cmsys/RegularExpression.hxx>
 
 
 static std::string cmIfCommandError(
-  cmMakefile* mf, std::vector<std::string> const& args)
+  cmMakefile* mf, std::vector<cmExpandedCommandArgument> const& args)
 {
   cmLocalGenerator* lg = mf->GetLocalGenerator();
   std::string err = "given arguments:\n ";
-  for(std::vector<std::string>::const_iterator i = args.begin();
+  for(std::vector<cmExpandedCommandArgument>::const_iterator i = args.begin();
       i != args.end(); ++i)
     {
     err += " ";
-    err += lg->EscapeForCMake(*i);
+    err += lg->EscapeForCMake(i->GetValue());
     }
   err += "\n";
   return err;
@@ -103,14 +105,16 @@
 
             std::string errorString;
 
-            std::vector<std::string> expandedArguments;
+            std::vector<cmExpandedCommandArgument> expandedArguments;
             mf.ExpandArguments(this->Functions[c].Arguments,
                                expandedArguments);
 
             cmake::MessageType messType;
-            bool isTrue =
-              cmIfCommand::IsTrue(expandedArguments, errorString,
-                                  &mf, messType);
+
+            cmConditionEvaluator conditionEvaluator(mf);
+
+            bool isTrue = conditionEvaluator.IsTrue(
+              expandedArguments, errorString, messType);
 
             if (errorString.size())
               {
@@ -185,13 +189,15 @@
 {
   std::string errorString;
 
-  std::vector<std::string> expandedArguments;
+  std::vector<cmExpandedCommandArgument> expandedArguments;
   this->Makefile->ExpandArguments(args, expandedArguments);
 
   cmake::MessageType status;
-  bool isTrue =
-    cmIfCommand::IsTrue(expandedArguments,errorString,
-                        this->Makefile, status);
+
+  cmConditionEvaluator conditionEvaluator(*(this->Makefile));
+
+  bool isTrue = conditionEvaluator.IsTrue(
+    expandedArguments, errorString, status);
 
   if (errorString.size())
     {
@@ -222,698 +228,3 @@
 
   return true;
 }
-
-namespace
-{
-  //=========================================================================
-  bool GetBooleanValue(std::string& arg, cmMakefile* mf)
-  {
-  // Check basic constants.
-  if (arg == "0")
-    {
-    return false;
-    }
-  if (arg == "1")
-    {
-    return true;
-    }
-
-  // Check named constants.
-  if (cmSystemTools::IsOn(arg.c_str()))
-    {
-    return true;
-    }
-  if (cmSystemTools::IsOff(arg.c_str()))
-    {
-    return false;
-    }
-
-  // Check for numbers.
-  if(!arg.empty())
-    {
-    char* end;
-    double d = strtod(arg.c_str(), &end);
-    if(*end == '\0')
-      {
-      // The whole string is a number.  Use C conversion to bool.
-      return d? true:false;
-      }
-    }
-
-  // Check definition.
-  const char* def = mf->GetDefinition(arg);
-  return !cmSystemTools::IsOff(def);
-  }
-
-  //=========================================================================
-  // Boolean value behavior from CMake 2.6.4 and below.
-  bool GetBooleanValueOld(std::string const& arg, cmMakefile* mf, bool one)
-  {
-  if(one)
-    {
-    // Old IsTrue behavior for single argument.
-    if(arg == "0")
-      { return false; }
-    else if(arg == "1")
-      { return true; }
-    else
-      { return !cmSystemTools::IsOff(mf->GetDefinition(arg)); }
-    }
-  else
-    {
-    // Old GetVariableOrNumber behavior.
-    const char* def = mf->GetDefinition(arg);
-    if(!def && atoi(arg.c_str()))
-      {
-      def = arg.c_str();
-      }
-    return !cmSystemTools::IsOff(def);
-    }
-  }
-
-  //=========================================================================
-  // returns the resulting boolean value
-  bool GetBooleanValueWithAutoDereference(
-    std::string &newArg,
-    cmMakefile *makefile,
-    std::string &errorString,
-    cmPolicies::PolicyStatus Policy12Status,
-    cmake::MessageType &status,
-    bool oneArg = false)
-  {
-  // Use the policy if it is set.
-  if (Policy12Status == cmPolicies::NEW)
-    {
-    return GetBooleanValue(newArg, makefile);
-    }
-  else if (Policy12Status == cmPolicies::OLD)
-    {
-    return GetBooleanValueOld(newArg, makefile, oneArg);
-    }
-
-  // Check policy only if old and new results differ.
-  bool newResult = GetBooleanValue(newArg, makefile);
-  bool oldResult = GetBooleanValueOld(newArg, makefile, oneArg);
-  if(newResult != oldResult)
-    {
-    switch(Policy12Status)
-      {
-      case cmPolicies::WARN:
-        {
-        cmPolicies* policies = makefile->GetPolicies();
-        errorString = "An argument named \"" + newArg
-          + "\" appears in a conditional statement.  "
-          + policies->GetPolicyWarning(cmPolicies::CMP0012);
-        status = cmake::AUTHOR_WARNING;
-        }
-      case cmPolicies::OLD:
-        return oldResult;
-      case cmPolicies::REQUIRED_IF_USED:
-      case cmPolicies::REQUIRED_ALWAYS:
-        {
-        cmPolicies* policies = makefile->GetPolicies();
-        errorString = "An argument named \"" + newArg
-          + "\" appears in a conditional statement.  "
-          + policies->GetRequiredPolicyError(cmPolicies::CMP0012);
-        status = cmake::FATAL_ERROR;
-        }
-      case cmPolicies::NEW:
-        break;
-      }
-    }
-  return newResult;
-  }
-
-  //=========================================================================
-  void IncrementArguments(std::list<std::string> &newArgs,
-                          std::list<std::string>::iterator &argP1,
-                          std::list<std::string>::iterator &argP2)
-  {
-    if (argP1  != newArgs.end())
-      {
-      argP1++;
-      argP2 = argP1;
-      if (argP1  != newArgs.end())
-        {
-        argP2++;
-        }
-      }
-  }
-
-  //=========================================================================
-  // helper function to reduce code duplication
-  void HandlePredicate(bool value, int &reducible,
-                       std::list<std::string>::iterator &arg,
-                       std::list<std::string> &newArgs,
-                       std::list<std::string>::iterator &argP1,
-                       std::list<std::string>::iterator &argP2)
-  {
-    if(value)
-      {
-      *arg = "1";
-      }
-    else
-      {
-      *arg = "0";
-      }
-    newArgs.erase(argP1);
-    argP1 = arg;
-    IncrementArguments(newArgs,argP1,argP2);
-    reducible = 1;
-  }
-
-  //=========================================================================
-  // helper function to reduce code duplication
-  void HandleBinaryOp(bool value, int &reducible,
-                       std::list<std::string>::iterator &arg,
-                       std::list<std::string> &newArgs,
-                       std::list<std::string>::iterator &argP1,
-                       std::list<std::string>::iterator &argP2)
-  {
-    if(value)
-      {
-      *arg = "1";
-      }
-    else
-      {
-      *arg = "0";
-      }
-    newArgs.erase(argP2);
-    newArgs.erase(argP1);
-    argP1 = arg;
-    IncrementArguments(newArgs,argP1,argP2);
-    reducible = 1;
-  }
-
-  //=========================================================================
-  // level 0 processes parenthetical expressions
-  bool HandleLevel0(std::list<std::string> &newArgs,
-                    cmMakefile *makefile,
-                    std::string &errorString,
-                    cmake::MessageType &status)
-  {
-  int reducible;
-  do
-    {
-    reducible = 0;
-    std::list<std::string>::iterator arg = newArgs.begin();
-    while (arg != newArgs.end())
-      {
-      if (*arg == "(")
-        {
-        // search for the closing paren for this opening one
-        std::list<std::string>::iterator argClose;
-        argClose = arg;
-        argClose++;
-        unsigned int depth = 1;
-        while (argClose != newArgs.end() && depth)
-          {
-          if (*argClose == "(")
-            {
-              depth++;
-            }
-          if (*argClose == ")")
-            {
-              depth--;
-            }
-          argClose++;
-          }
-        if (depth)
-          {
-          errorString = "mismatched parenthesis in condition";
-          status = cmake::FATAL_ERROR;
-          return false;
-          }
-        // store the reduced args in this vector
-        std::vector<std::string> newArgs2;
-
-        // copy to the list structure
-        std::list<std::string>::iterator argP1 = arg;
-        argP1++;
-        for(; argP1 != argClose; argP1++)
-          {
-          newArgs2.push_back(*argP1);
-          }
-        newArgs2.pop_back();
-        // now recursively invoke IsTrue to handle the values inside the
-        // parenthetical expression
-        bool value =
-          cmIfCommand::IsTrue(newArgs2, errorString, makefile, status);
-        if(value)
-          {
-          *arg = "1";
-          }
-        else
-          {
-          *arg = "0";
-          }
-        argP1 = arg;
-        argP1++;
-        // remove the now evaluated parenthetical expression
-        newArgs.erase(argP1,argClose);
-        }
-      ++arg;
-      }
-    }
-  while (reducible);
-  return true;
-  }
-
-  //=========================================================================
-  // level one handles most predicates except for NOT
-  bool HandleLevel1(std::list<std::string> &newArgs,
-                    cmMakefile *makefile,
-                    std::string &, cmake::MessageType &)
-  {
-  int reducible;
-  do
-    {
-    reducible = 0;
-    std::list<std::string>::iterator arg = newArgs.begin();
-    std::list<std::string>::iterator argP1;
-    std::list<std::string>::iterator argP2;
-    while (arg != newArgs.end())
-      {
-      argP1 = arg;
-      IncrementArguments(newArgs,argP1,argP2);
-      // does a file exist
-      if (*arg == "EXISTS" && argP1  != newArgs.end())
-        {
-        HandlePredicate(
-          cmSystemTools::FileExists((argP1)->c_str()),
-          reducible, arg, newArgs, argP1, argP2);
-        }
-      // does a directory with this name exist
-      if (*arg == "IS_DIRECTORY" && argP1  != newArgs.end())
-        {
-        HandlePredicate(
-          cmSystemTools::FileIsDirectory((argP1)->c_str()),
-          reducible, arg, newArgs, argP1, argP2);
-        }
-      // does a symlink with this name exist
-      if (*arg == "IS_SYMLINK" && argP1  != newArgs.end())
-        {
-        HandlePredicate(
-          cmSystemTools::FileIsSymlink((argP1)->c_str()),
-          reducible, arg, newArgs, argP1, argP2);
-        }
-      // is the given path an absolute path ?
-      if (*arg == "IS_ABSOLUTE" && argP1  != newArgs.end())
-        {
-        HandlePredicate(
-          cmSystemTools::FileIsFullPath((argP1)->c_str()),
-          reducible, arg, newArgs, argP1, argP2);
-        }
-      // does a command exist
-      if (*arg == "COMMAND" && argP1  != newArgs.end())
-        {
-        HandlePredicate(
-          makefile->CommandExists((argP1)->c_str()),
-          reducible, arg, newArgs, argP1, argP2);
-        }
-      // does a policy exist
-      if (*arg == "POLICY" && argP1 != newArgs.end())
-        {
-        cmPolicies::PolicyID pid;
-        HandlePredicate(
-          makefile->GetPolicies()->GetPolicyID((argP1)->c_str(), pid),
-          reducible, arg, newArgs, argP1, argP2);
-        }
-      // does a target exist
-      if (*arg == "TARGET" && argP1 != newArgs.end())
-        {
-        HandlePredicate(
-          makefile->FindTargetToUse(*argP1)?true:false,
-          reducible, arg, newArgs, argP1, argP2);
-        }
-      // is a variable defined
-      if (*arg == "DEFINED" && argP1  != newArgs.end())
-        {
-        size_t argP1len = argP1->size();
-        bool bdef = false;
-        if(argP1len > 4 && argP1->substr(0, 4) == "ENV{" &&
-           argP1->operator[](argP1len-1) == '}')
-          {
-          std::string env = argP1->substr(4, argP1len-5);
-          bdef = cmSystemTools::GetEnv(env.c_str())?true:false;
-          }
-        else
-          {
-          bdef = makefile->IsDefinitionSet(*(argP1));
-          }
-        HandlePredicate(bdef, reducible, arg, newArgs, argP1, argP2);
-        }
-      ++arg;
-      }
-    }
-  while (reducible);
-  return true;
-  }
-
-  //=========================================================================
-  // level two handles most binary operations except for AND  OR
-  bool HandleLevel2(std::list<std::string> &newArgs,
-                    cmMakefile *makefile,
-                    std::string &errorString,
-                    cmake::MessageType &status)
-  {
-  int reducible;
-  const char *def;
-  const char *def2;
-  do
-    {
-    reducible = 0;
-    std::list<std::string>::iterator arg = newArgs.begin();
-    std::list<std::string>::iterator argP1;
-    std::list<std::string>::iterator argP2;
-    while (arg != newArgs.end())
-      {
-      argP1 = arg;
-      IncrementArguments(newArgs,argP1,argP2);
-      if (argP1 != newArgs.end() && argP2 != newArgs.end() &&
-        *(argP1) == "MATCHES")
-        {
-        def = cmIfCommand::GetVariableOrString(*arg, makefile);
-        const char* rex = (argP2)->c_str();
-        makefile->ClearMatches();
-        cmsys::RegularExpression regEntry;
-        if ( !regEntry.compile(rex) )
-          {
-          cmOStringStream error;
-          error << "Regular expression \"" << rex << "\" cannot compile";
-          errorString = error.str();
-          status = cmake::FATAL_ERROR;
-          return false;
-          }
-        if (regEntry.find(def))
-          {
-          makefile->StoreMatches(regEntry);
-          *arg = "1";
-          }
-        else
-          {
-          *arg = "0";
-          }
-        newArgs.erase(argP2);
-        newArgs.erase(argP1);
-        argP1 = arg;
-        IncrementArguments(newArgs,argP1,argP2);
-        reducible = 1;
-        }
-
-      if (argP1 != newArgs.end() && *arg == "MATCHES")
-        {
-        *arg = "0";
-        newArgs.erase(argP1);
-        argP1 = arg;
-        IncrementArguments(newArgs,argP1,argP2);
-        reducible = 1;
-        }
-
-      if (argP1 != newArgs.end() && argP2 != newArgs.end() &&
-        (*(argP1) == "LESS" || *(argP1) == "GREATER" ||
-         *(argP1) == "EQUAL"))
-        {
-        def = cmIfCommand::GetVariableOrString(*arg, makefile);
-        def2 = cmIfCommand::GetVariableOrString(*argP2, makefile);
-        double lhs;
-        double rhs;
-        bool result;
-        if(sscanf(def, "%lg", &lhs) != 1 ||
-           sscanf(def2, "%lg", &rhs) != 1)
-          {
-          result = false;
-          }
-        else if (*(argP1) == "LESS")
-          {
-          result = (lhs < rhs);
-          }
-        else if (*(argP1) == "GREATER")
-          {
-          result = (lhs > rhs);
-          }
-        else
-          {
-          result = (lhs == rhs);
-          }
-        HandleBinaryOp(result,
-          reducible, arg, newArgs, argP1, argP2);
-        }
-
-      if (argP1 != newArgs.end() && argP2 != newArgs.end() &&
-        (*(argP1) == "STRLESS" ||
-         *(argP1) == "STREQUAL" ||
-         *(argP1) == "STRGREATER"))
-        {
-        def = cmIfCommand::GetVariableOrString(*arg, makefile);
-        def2 = cmIfCommand::GetVariableOrString(*argP2, makefile);
-        int val = strcmp(def,def2);
-        bool result;
-        if (*(argP1) == "STRLESS")
-          {
-          result = (val < 0);
-          }
-        else if (*(argP1) == "STRGREATER")
-          {
-          result = (val > 0);
-          }
-        else // strequal
-          {
-          result = (val == 0);
-          }
-        HandleBinaryOp(result,
-          reducible, arg, newArgs, argP1, argP2);
-        }
-
-      if (argP1 != newArgs.end() && argP2 != newArgs.end() &&
-        (*(argP1) == "VERSION_LESS" || *(argP1) == "VERSION_GREATER" ||
-         *(argP1) == "VERSION_EQUAL"))
-        {
-        def = cmIfCommand::GetVariableOrString(*arg, makefile);
-        def2 = cmIfCommand::GetVariableOrString(*argP2, makefile);
-        cmSystemTools::CompareOp op = cmSystemTools::OP_EQUAL;
-        if(*argP1 == "VERSION_LESS")
-          {
-          op = cmSystemTools::OP_LESS;
-          }
-        else if(*argP1 == "VERSION_GREATER")
-          {
-          op = cmSystemTools::OP_GREATER;
-          }
-        bool result = cmSystemTools::VersionCompare(op, def, def2);
-        HandleBinaryOp(result,
-          reducible, arg, newArgs, argP1, argP2);
-        }
-
-      // is file A newer than file B
-      if (argP1 != newArgs.end() && argP2 != newArgs.end() &&
-          *(argP1) == "IS_NEWER_THAN")
-        {
-        int fileIsNewer=0;
-        bool success=cmSystemTools::FileTimeCompare(arg->c_str(),
-            (argP2)->c_str(),
-            &fileIsNewer);
-        HandleBinaryOp(
-          (success==false || fileIsNewer==1 || fileIsNewer==0),
-          reducible, arg, newArgs, argP1, argP2);
-        }
-
-      ++arg;
-      }
-    }
-  while (reducible);
-  return true;
-  }
-
-  //=========================================================================
-  // level 3 handles NOT
-  bool HandleLevel3(std::list<std::string> &newArgs,
-                    cmMakefile *makefile,
-                    std::string &errorString,
-                    cmPolicies::PolicyStatus Policy12Status,
-                    cmake::MessageType &status)
-  {
-  int reducible;
-  do
-    {
-    reducible = 0;
-    std::list<std::string>::iterator arg = newArgs.begin();
-    std::list<std::string>::iterator argP1;
-    std::list<std::string>::iterator argP2;
-    while (arg != newArgs.end())
-      {
-      argP1 = arg;
-      IncrementArguments(newArgs,argP1,argP2);
-      if (argP1 != newArgs.end() && *arg == "NOT")
-        {
-        bool rhs = GetBooleanValueWithAutoDereference(*argP1, makefile,
-                                                      errorString,
-                                                      Policy12Status,
-                                                      status);
-        HandlePredicate(!rhs, reducible, arg, newArgs, argP1, argP2);
-        }
-      ++arg;
-      }
-    }
-  while (reducible);
-  return true;
-  }
-
-  //=========================================================================
-  // level 4 handles AND OR
-  bool HandleLevel4(std::list<std::string> &newArgs,
-                    cmMakefile *makefile,
-                    std::string &errorString,
-                    cmPolicies::PolicyStatus Policy12Status,
-                    cmake::MessageType &status)
-  {
-  int reducible;
-  bool lhs;
-  bool rhs;
-  do
-    {
-    reducible = 0;
-    std::list<std::string>::iterator arg = newArgs.begin();
-    std::list<std::string>::iterator argP1;
-    std::list<std::string>::iterator argP2;
-    while (arg != newArgs.end())
-      {
-      argP1 = arg;
-      IncrementArguments(newArgs,argP1,argP2);
-      if (argP1 != newArgs.end() && *(argP1) == "AND" &&
-        argP2 != newArgs.end())
-        {
-        lhs = GetBooleanValueWithAutoDereference(*arg, makefile,
-                                                 errorString,
-                                                 Policy12Status,
-                                                 status);
-        rhs = GetBooleanValueWithAutoDereference(*argP2, makefile,
-                                                 errorString,
-                                                 Policy12Status,
-                                                 status);
-        HandleBinaryOp((lhs && rhs),
-          reducible, arg, newArgs, argP1, argP2);
-        }
-
-      if (argP1 != newArgs.end() && *(argP1) == "OR" &&
-        argP2 != newArgs.end())
-        {
-        lhs = GetBooleanValueWithAutoDereference(*arg, makefile,
-                                                 errorString,
-                                                 Policy12Status,
-                                                 status);
-        rhs = GetBooleanValueWithAutoDereference(*argP2, makefile,
-                                                 errorString,
-                                                 Policy12Status,
-                                                 status);
-        HandleBinaryOp((lhs || rhs),
-          reducible, arg, newArgs, argP1, argP2);
-        }
-      ++arg;
-      }
-    }
-  while (reducible);
-  return true;
-  }
-}
-
-
-//=========================================================================
-// order of operations,
-// 1.   ( )   -- parenthetical groups
-// 2.  IS_DIRECTORY EXISTS COMMAND DEFINED etc predicates
-// 3. MATCHES LESS GREATER EQUAL STRLESS STRGREATER STREQUAL etc binary ops
-// 4. NOT
-// 5. AND OR
-//
-// There is an issue on whether the arguments should be values of references,
-// for example IF (FOO AND BAR) should that compare the strings FOO and BAR
-// or should it really do IF (${FOO} AND ${BAR}) Currently IS_DIRECTORY
-// EXISTS COMMAND and DEFINED all take values. EQUAL, LESS and GREATER can
-// take numeric values or variable names. STRLESS and STRGREATER take
-// variable names but if the variable name is not found it will use the name
-// directly. AND OR take variables or the values 0 or 1.
-
-
-bool cmIfCommand::IsTrue(const std::vector<std::string> &args,
-                         std::string &errorString, cmMakefile *makefile,
-                         cmake::MessageType &status)
-{
-  errorString = "";
-
-  // handle empty invocation
-  if (args.size() < 1)
-    {
-    return false;
-    }
-
-  // store the reduced args in this vector
-  std::list<std::string> newArgs;
-
-  // copy to the list structure
-  for(unsigned int i = 0; i < args.size(); ++i)
-    {
-    newArgs.push_back(args[i]);
-    }
-
-  // now loop through the arguments and see if we can reduce any of them
-  // we do this multiple times. Once for each level of precedence
-  // parens
-  if (!HandleLevel0(newArgs, makefile, errorString, status))
-    {
-    return false;
-    }
-  //predicates
-  if (!HandleLevel1(newArgs, makefile, errorString, status))
-    {
-    return false;
-    }
-  // binary ops
-  if (!HandleLevel2(newArgs, makefile, errorString, status))
-    {
-    return false;
-    }
-
-  // used to store the value of policy CMP0012 for performance
-  cmPolicies::PolicyStatus Policy12Status =
-    makefile->GetPolicyStatus(cmPolicies::CMP0012);
-
-  // NOT
-  if (!HandleLevel3(newArgs, makefile, errorString,
-                    Policy12Status, status))
-    {
-    return false;
-    }
-  // AND OR
-  if (!HandleLevel4(newArgs, makefile, errorString,
-                    Policy12Status, status))
-    {
-    return false;
-    }
-
-  // now at the end there should only be one argument left
-  if (newArgs.size() != 1)
-    {
-    errorString = "Unknown arguments specified";
-    status = cmake::FATAL_ERROR;
-    return false;
-    }
-
-  return GetBooleanValueWithAutoDereference(*(newArgs.begin()),
-                                            makefile,
-                                            errorString,
-                                            Policy12Status,
-                                            status, true);
-}
-
-//=========================================================================
-const char* cmIfCommand::GetVariableOrString(const std::string& str,
-                                             const cmMakefile* mf)
-{
-  const char* def = mf->GetDefinition(str);
-  if(!def)
-    {
-    def = str.c_str();
-    }
-  return def;
-}
diff --git a/Source/cmIfCommand.h b/Source/cmIfCommand.h
index 814c052..689efce 100644
--- a/Source/cmIfCommand.h
+++ b/Source/cmIfCommand.h
@@ -70,17 +70,9 @@
    */
   virtual bool IsScriptable() const { return true; }
 
-  // this is a shared function for both If and Else to determine if the
-  // arguments were valid, and if so, was the response true. If there is
-  // an error, the errorString will be set.
-  static bool IsTrue(const std::vector<std::string> &args,
-    std::string &errorString, cmMakefile *mf,
-    cmake::MessageType &status);
-
-  // Get a definition from the makefile.  If it doesn't exist,
-  // return the original string.
-  static const char* GetVariableOrString(const std::string& str,
-                                         const cmMakefile* mf);
+  // Filter the given variable definition based on policy CMP0054.
+  static const char* GetDefinitionIfUnquoted(
+    const cmMakefile* mf, cmExpandedCommandArgument const& argument);
 
   cmTypeMacro(cmIfCommand, cmCommand);
 };
diff --git a/Source/cmInstallCommand.cxx b/Source/cmInstallCommand.cxx
index 0041122..ec500d9 100644
--- a/Source/cmInstallCommand.cxx
+++ b/Source/cmInstallCommand.cxx
@@ -25,9 +25,12 @@
 static cmInstallTargetGenerator* CreateInstallTargetGenerator(cmTarget& target,
      const cmInstallCommandArguments& args, bool impLib, bool forceOpt = false)
 {
+  cmInstallGenerator::MessageLevel message =
+    cmInstallGenerator::SelectMessageLevel(target.GetMakefile());
   return new cmInstallTargetGenerator(target, args.GetDestination().c_str(),
                         impLib, args.GetPermissions().c_str(),
                         args.GetConfigurations(), args.GetComponent().c_str(),
+                        message,
                         args.GetOptional() || forceOpt);
 }
 
@@ -36,10 +39,13 @@
     const std::vector<std::string>& absFiles,
     const cmInstallCommandArguments& args, bool programs)
 {
+  cmInstallGenerator::MessageLevel message =
+    cmInstallGenerator::SelectMessageLevel(mf);
   return new cmInstallFilesGenerator(mf,
                         absFiles, args.GetDestination().c_str(),
                         programs, args.GetPermissions().c_str(),
                         args.GetConfigurations(), args.GetComponent().c_str(),
+                        message,
                         args.GetRename().c_str(), args.GetOptional());
 }
 
@@ -911,6 +917,7 @@
   Doing doing = DoingDirs;
   bool in_match_mode = false;
   bool optional = false;
+  bool message_never = false;
   std::vector<std::string> dirs;
   const char* destination = 0;
   std::string permissions_file;
@@ -949,6 +956,21 @@
       optional = true;
       doing = DoingNone;
       }
+    else if(args[i] == "MESSAGE_NEVER")
+      {
+      if(in_match_mode)
+        {
+        cmOStringStream e;
+        e << args[0] << " does not allow \""
+          << args[i] << "\" after PATTERN or REGEX.";
+        this->SetError(e.str());
+        return false;
+        }
+
+      // Mark the rule as quiet.
+      message_never = true;
+      doing = DoingNone;
+      }
     else if(args[i] == "PATTERN")
       {
       // Switch to a new pattern match rule.
@@ -1208,6 +1230,9 @@
     return false;
     }
 
+  cmInstallGenerator::MessageLevel message =
+    cmInstallGenerator::SelectMessageLevel(this->Makefile, message_never);
+
   // Create the directory install generator.
   this->Makefile->AddInstallGenerator(
     new cmInstallDirectoryGenerator(dirs, destination,
@@ -1215,6 +1240,7 @@
                                     permissions_dir.c_str(),
                                     configurations,
                                     component.c_str(),
+                                    message,
                                     literal_args.c_str(),
                                     optional));
 
@@ -1333,13 +1359,16 @@
       }
     }
 
+  cmInstallGenerator::MessageLevel message =
+    cmInstallGenerator::SelectMessageLevel(this->Makefile);
+
   // Create the export install generator.
   cmInstallExportGenerator* exportGenerator =
     new cmInstallExportGenerator(
       exportSet,
       ica.GetDestination().c_str(),
       ica.GetPermissions().c_str(), ica.GetConfigurations(),
-      ica.GetComponent().c_str(), fname.c_str(),
+      ica.GetComponent().c_str(), message, fname.c_str(),
       name_space.GetCString(), exportOld.IsEnabled(), this->Makefile);
   this->Makefile->AddInstallGenerator(exportGenerator);
 
diff --git a/Source/cmInstallDirectoryGenerator.cxx b/Source/cmInstallDirectoryGenerator.cxx
index ddf7d08..8c13bab 100644
--- a/Source/cmInstallDirectoryGenerator.cxx
+++ b/Source/cmInstallDirectoryGenerator.cxx
@@ -21,9 +21,11 @@
                               const char* dir_permissions,
                               std::vector<std::string> const& configurations,
                               const char* component,
+                              MessageLevel message,
                               const char* literal_args,
                               bool optional):
-  cmInstallGenerator(dest, configurations, component), Directories(dirs),
+  cmInstallGenerator(dest, configurations, component, message),
+  Directories(dirs),
   FilePermissions(file_permissions), DirPermissions(dir_permissions),
   LiteralArguments(literal_args), Optional(optional)
 {
diff --git a/Source/cmInstallDirectoryGenerator.h b/Source/cmInstallDirectoryGenerator.h
index d76ef3c..165ab91 100644
--- a/Source/cmInstallDirectoryGenerator.h
+++ b/Source/cmInstallDirectoryGenerator.h
@@ -26,6 +26,7 @@
                               const char* dir_permissions,
                               std::vector<std::string> const& configurations,
                               const char* component,
+                              MessageLevel message,
                               const char* literal_args,
                               bool optional = false);
   virtual ~cmInstallDirectoryGenerator();
diff --git a/Source/cmInstallExportGenerator.cxx b/Source/cmInstallExportGenerator.cxx
index 9a17052..ddfd6c5 100644
--- a/Source/cmInstallExportGenerator.cxx
+++ b/Source/cmInstallExportGenerator.cxx
@@ -32,10 +32,11 @@
   const char* file_permissions,
   std::vector<std::string> const& configurations,
   const char* component,
+  MessageLevel message,
   const char* filename, const char* name_space,
   bool exportOld,
   cmMakefile* mf)
-  :cmInstallGenerator(destination, configurations, component)
+  :cmInstallGenerator(destination, configurations, component, message)
   ,ExportSet(exportSet)
   ,FilePermissions(file_permissions)
   ,FileName(filename)
diff --git a/Source/cmInstallExportGenerator.h b/Source/cmInstallExportGenerator.h
index 37b5593..eb8c28b 100644
--- a/Source/cmInstallExportGenerator.h
+++ b/Source/cmInstallExportGenerator.h
@@ -30,6 +30,7 @@
                            const char* dest, const char* file_permissions,
                            const std::vector<std::string>& configurations,
                            const char* component,
+                           MessageLevel message,
                            const char* filename, const char* name_space,
                            bool exportOld, cmMakefile* mf);
   ~cmInstallExportGenerator();
diff --git a/Source/cmInstallFilesCommand.cxx b/Source/cmInstallFilesCommand.cxx
index 7eabbef..f106e1a 100644
--- a/Source/cmInstallFilesCommand.cxx
+++ b/Source/cmInstallFilesCommand.cxx
@@ -132,11 +132,13 @@
   std::string no_component = this->Makefile->GetSafeDefinition(
                                        "CMAKE_INSTALL_DEFAULT_COMPONENT_NAME");
   std::vector<std::string> no_configurations;
+  cmInstallGenerator::MessageLevel message =
+    cmInstallGenerator::SelectMessageLevel(this->Makefile);
   this->Makefile->AddInstallGenerator(
     new cmInstallFilesGenerator(this->Makefile, this->Files,
                                 destination.c_str(), false,
                                 no_permissions, no_configurations,
-                                no_component.c_str(), no_rename));
+                                no_component.c_str(), message, no_rename));
 }
 
 
diff --git a/Source/cmInstallFilesGenerator.cxx b/Source/cmInstallFilesGenerator.cxx
index b2be82e..91b102a 100644
--- a/Source/cmInstallFilesGenerator.cxx
+++ b/Source/cmInstallFilesGenerator.cxx
@@ -23,9 +23,10 @@
                           const char* file_permissions,
                           std::vector<std::string> const& configurations,
                           const char* component,
+                          MessageLevel message,
                           const char* rename,
                           bool optional):
-  cmInstallGenerator(dest, configurations, component),
+  cmInstallGenerator(dest, configurations, component, message),
   Makefile(mf),
   Files(files), Programs(programs),
   FilePermissions(file_permissions),
diff --git a/Source/cmInstallFilesGenerator.h b/Source/cmInstallFilesGenerator.h
index 23bf935..0dbd712 100644
--- a/Source/cmInstallFilesGenerator.h
+++ b/Source/cmInstallFilesGenerator.h
@@ -28,6 +28,7 @@
                           const char* file_permissions,
                           std::vector<std::string> const& configurations,
                           const char* component,
+                          MessageLevel message,
                           const char* rename,
                           bool optional = false);
   virtual ~cmInstallFilesGenerator();
diff --git a/Source/cmInstallGenerator.cxx b/Source/cmInstallGenerator.cxx
index 9370e48..b261cbf 100644
--- a/Source/cmInstallGenerator.cxx
+++ b/Source/cmInstallGenerator.cxx
@@ -11,16 +11,19 @@
 ============================================================================*/
 #include "cmInstallGenerator.h"
 
+#include "cmMakefile.h"
 #include "cmSystemTools.h"
 
 //----------------------------------------------------------------------------
 cmInstallGenerator
 ::cmInstallGenerator(const char* destination,
                      std::vector<std::string> const& configurations,
-                     const char* component):
+                     const char* component,
+                     MessageLevel message):
   cmScriptGenerator("CMAKE_INSTALL_CONFIG_NAME", configurations),
   Destination(destination? destination:""),
-  Component(component? component:"")
+  Component(component? component:""),
+  Message(message)
 {
 }
 
@@ -96,6 +99,13 @@
     {
     os << " OPTIONAL";
     }
+  switch(this->Message)
+    {
+    case MessageDefault: break;
+    case MessageAlways: os << " MESSAGE_ALWAYS"; break;
+    case MessageLazy:   os << " MESSAGE_LAZY"; break;
+    case MessageNever:  os << " MESSAGE_NEVER"; break;
+    }
   if(permissions_file && *permissions_file)
     {
     os << " PERMISSIONS" << permissions_file;
@@ -180,3 +190,27 @@
   result += this->Destination;
   return result;
 }
+
+//----------------------------------------------------------------------------
+cmInstallGenerator::MessageLevel
+cmInstallGenerator::SelectMessageLevel(cmMakefile* mf, bool never)
+{
+  if(never)
+    {
+    return MessageNever;
+    }
+  std::string m = mf->GetSafeDefinition("CMAKE_INSTALL_MESSAGE");
+  if(m == "ALWAYS")
+    {
+    return MessageAlways;
+    }
+  if(m == "LAZY")
+    {
+    return MessageLazy;
+    }
+  if(m == "NEVER")
+    {
+    return MessageNever;
+    }
+  return MessageDefault;
+}
diff --git a/Source/cmInstallGenerator.h b/Source/cmInstallGenerator.h
index c72e9e9..38aac91 100644
--- a/Source/cmInstallGenerator.h
+++ b/Source/cmInstallGenerator.h
@@ -16,6 +16,7 @@
 #include "cmScriptGenerator.h"
 
 class cmLocalGenerator;
+class cmMakefile;
 
 /** \class cmInstallGenerator
  * \brief Support class for generating install scripts.
@@ -24,9 +25,18 @@
 class cmInstallGenerator: public cmScriptGenerator
 {
 public:
+  enum MessageLevel
+  {
+    MessageDefault,
+    MessageAlways,
+    MessageLazy,
+    MessageNever
+  };
+
   cmInstallGenerator(const char* destination,
                      std::vector<std::string> const& configurations,
-                     const char* component);
+                     const char* component,
+                     MessageLevel message);
   virtual ~cmInstallGenerator();
 
   void AddInstallRule(
@@ -50,6 +60,9 @@
   /** Test if this generator installs something for a given configuration.  */
   bool InstallsForConfig(const std::string& config);
 
+  /** Select message level from CMAKE_INSTALL_MESSAGE or 'never'.  */
+  static MessageLevel SelectMessageLevel(cmMakefile* mf, bool never = false);
+
 protected:
   virtual void GenerateScript(std::ostream& os);
 
@@ -58,6 +71,7 @@
   // Information shared by most generator types.
   std::string Destination;
   std::string Component;
+  MessageLevel Message;
 };
 
 #endif
diff --git a/Source/cmInstallProgramsCommand.cxx b/Source/cmInstallProgramsCommand.cxx
index 597f7ee..0405769 100644
--- a/Source/cmInstallProgramsCommand.cxx
+++ b/Source/cmInstallProgramsCommand.cxx
@@ -93,11 +93,13 @@
   std::string no_component = this->Makefile->GetSafeDefinition(
                                        "CMAKE_INSTALL_DEFAULT_COMPONENT_NAME");
   std::vector<std::string> no_configurations;
+  cmInstallGenerator::MessageLevel message =
+    cmInstallGenerator::SelectMessageLevel(this->Makefile);
   this->Makefile->AddInstallGenerator(
     new cmInstallFilesGenerator(this->Makefile, this->Files,
                                 destination.c_str(), true,
                                 no_permissions, no_configurations,
-                                no_component.c_str(), no_rename));
+                                no_component.c_str(), message, no_rename));
 }
 
 /**
diff --git a/Source/cmInstallScriptGenerator.cxx b/Source/cmInstallScriptGenerator.cxx
index 1ecf021..933aa07 100644
--- a/Source/cmInstallScriptGenerator.cxx
+++ b/Source/cmInstallScriptGenerator.cxx
@@ -15,7 +15,7 @@
 cmInstallScriptGenerator
 ::cmInstallScriptGenerator(const char* script, bool code,
                            const char* component) :
-  cmInstallGenerator(0, std::vector<std::string>(), component),
+  cmInstallGenerator(0, std::vector<std::string>(), component, MessageDefault),
   Script(script), Code(code)
 {
 }
diff --git a/Source/cmInstallTargetGenerator.cxx b/Source/cmInstallTargetGenerator.cxx
index ec2b518..d689c89 100644
--- a/Source/cmInstallTargetGenerator.cxx
+++ b/Source/cmInstallTargetGenerator.cxx
@@ -24,8 +24,10 @@
 ::cmInstallTargetGenerator(cmTarget& t, const char* dest, bool implib,
                            const char* file_permissions,
                            std::vector<std::string> const& configurations,
-                           const char* component, bool optional):
-  cmInstallGenerator(dest, configurations, component), Target(&t),
+                           const char* component,
+                           MessageLevel message,
+                           bool optional):
+  cmInstallGenerator(dest, configurations, component, message), Target(&t),
   ImportLibrary(implib), FilePermissions(file_permissions), Optional(optional)
 {
   this->ActionsPerConfig = true;
@@ -213,6 +215,20 @@
       filesFrom.push_back(from1);
       filesTo.push_back(to1);
       }
+    else if(this->Target->IsCFBundleOnApple())
+      {
+      // Install the whole app bundle directory.
+      type = cmInstallType_DIRECTORY;
+      literal_args += " USE_SOURCE_PERMISSIONS";
+
+      std::string targetNameBase = targetName.substr(0, targetName.find('/'));
+
+      std::string from1 = fromDirConfig + targetNameBase;
+      std::string to1 = toDir + targetName;
+
+      filesFrom.push_back(from1);
+      filesTo.push_back(to1);
+      }
     else
       {
       bool haveNamelink = false;
@@ -661,46 +677,72 @@
     return;
     }
 
-  if(this->Target->GetMakefile()->IsOn("CMAKE_PLATFORM_HAS_INSTALLNAME"))
+  cmMakefile* mf = this->Target->GetMakefile();
+
+  if(mf->IsOn("CMAKE_PLATFORM_HAS_INSTALLNAME"))
     {
     // If using install_name_tool, set up the rules to modify the rpaths.
     std::string installNameTool =
-      this->Target->GetMakefile()->
-      GetSafeDefinition("CMAKE_INSTALL_NAME_TOOL");
+      mf->GetSafeDefinition("CMAKE_INSTALL_NAME_TOOL");
 
     std::vector<std::string> oldRuntimeDirs, newRuntimeDirs;
     cli->GetRPath(oldRuntimeDirs, false);
     cli->GetRPath(newRuntimeDirs, true);
 
-    // Note: These paths are kept unique to avoid install_name_tool corruption.
-    std::set<std::string> runpaths;
-    for(std::vector<std::string>::const_iterator i = oldRuntimeDirs.begin();
-        i != oldRuntimeDirs.end(); ++i)
-      {
-      std::string runpath = this->Target->GetMakefile()->GetLocalGenerator()->
-        GetGlobalGenerator()->ExpandCFGIntDir(*i, config);
+    std::string darwin_major_version_s =
+      mf->GetSafeDefinition("DARWIN_MAJOR_VERSION");
 
-      if(runpaths.find(runpath) == runpaths.end())
-        {
-        runpaths.insert(runpath);
-        os << indent << "execute_process(COMMAND " << installNameTool << "\n";
-        os << indent << "  -delete_rpath \"" << runpath << "\"\n";
-        os << indent << "  \"" << toDestDirPath << "\")\n";
-        }
+    std::stringstream ss(darwin_major_version_s);
+    int darwin_major_version;
+    ss >> darwin_major_version;
+    if(!ss.fail() && darwin_major_version <= 9 &&
+       (!oldRuntimeDirs.empty() || !newRuntimeDirs.empty())
+      )
+      {
+      cmOStringStream msg;
+      msg << "WARNING: Target \"" << this->Target->GetName()
+        << "\" has runtime paths which cannot be changed during install.  "
+        << "To change runtime paths, OS X version 10.6 or newer is required.  "
+        << "Therefore, runtime paths will not be changed when installing.  "
+        << "CMAKE_BUILD_WITH_INSTALL_RPATH may be used to work around"
+           " this limitation.";
+      mf->IssueMessage(cmake::WARNING, msg.str());
       }
-
-    runpaths.clear();
-    for(std::vector<std::string>::const_iterator i = newRuntimeDirs.begin();
-        i != newRuntimeDirs.end(); ++i)
+    else
       {
-      std::string runpath = this->Target->GetMakefile()->GetLocalGenerator()->
-        GetGlobalGenerator()->ExpandCFGIntDir(*i, config);
-
-      if(runpaths.find(runpath) == runpaths.end())
+      // Note: These paths are kept unique to avoid
+      // install_name_tool corruption.
+      std::set<std::string> runpaths;
+      for(std::vector<std::string>::const_iterator i = oldRuntimeDirs.begin();
+          i != oldRuntimeDirs.end(); ++i)
         {
-        os << indent << "execute_process(COMMAND " << installNameTool << "\n";
-        os << indent << "  -add_rpath \"" << runpath << "\"\n";
-        os << indent << "  \"" << toDestDirPath << "\")\n";
+        std::string runpath =
+          mf->GetLocalGenerator()->
+          GetGlobalGenerator()->ExpandCFGIntDir(*i, config);
+
+        if(runpaths.find(runpath) == runpaths.end())
+          {
+          runpaths.insert(runpath);
+          os << indent << "execute_process(COMMAND " << installNameTool <<"\n";
+          os << indent << "  -delete_rpath \"" << runpath << "\"\n";
+          os << indent << "  \"" << toDestDirPath << "\")\n";
+          }
+        }
+
+      runpaths.clear();
+      for(std::vector<std::string>::const_iterator i = newRuntimeDirs.begin();
+          i != newRuntimeDirs.end(); ++i)
+        {
+        std::string runpath =
+          mf->GetLocalGenerator()->
+          GetGlobalGenerator()->ExpandCFGIntDir(*i, config);
+
+        if(runpaths.find(runpath) == runpaths.end())
+          {
+          os << indent << "execute_process(COMMAND " << installNameTool <<"\n";
+          os << indent << "  -add_rpath \"" << runpath << "\"\n";
+          os << indent << "  \"" << toDestDirPath << "\")\n";
+          }
         }
       }
     }
diff --git a/Source/cmInstallTargetGenerator.h b/Source/cmInstallTargetGenerator.h
index 0f21da7..7e5cc71 100644
--- a/Source/cmInstallTargetGenerator.h
+++ b/Source/cmInstallTargetGenerator.h
@@ -24,11 +24,11 @@
 public:
   cmInstallTargetGenerator(
     cmTarget& t, const char* dest, bool implib,
-    const char* file_permissions = "",
-    std::vector<std::string> const& configurations
-    = std::vector<std::string>(),
-    const char* component = "Unspecified",
-    bool optional = false
+    const char* file_permissions,
+    std::vector<std::string> const& configurations,
+    const char* component,
+    MessageLevel message,
+    bool optional
     );
   virtual ~cmInstallTargetGenerator();
 
diff --git a/Source/cmInstalledFile.cxx b/Source/cmInstalledFile.cxx
index 7813fcc..4b53752 100644
--- a/Source/cmInstalledFile.cxx
+++ b/Source/cmInstalledFile.cxx
@@ -77,6 +77,13 @@
 }
 
 //----------------------------------------------------------------------------
+bool cmInstalledFile::HasProperty(
+  const std::string& prop) const
+{
+  return this->Properties.find(prop) != this->Properties.end();
+}
+
+//----------------------------------------------------------------------------
 bool cmInstalledFile::GetProperty(
   const std::string& prop, std::string& value) const
 {
@@ -111,3 +118,14 @@
   bool isSet = this->GetProperty(prop, value);
   return isSet && cmSystemTools::IsOn(value.c_str());
 }
+
+//----------------------------------------------------------------------------
+void cmInstalledFile::GetPropertyAsList(const std::string& prop,
+  std::vector<std::string>& list) const
+{
+  std::string value;
+  this->GetProperty(prop, value);
+
+  list.clear();
+  cmSystemTools::ExpandListArgument(value, list);
+}
diff --git a/Source/cmInstalledFile.h b/Source/cmInstalledFile.h
index df28221..7134a4e 100644
--- a/Source/cmInstalledFile.h
+++ b/Source/cmInstalledFile.h
@@ -62,10 +62,15 @@
   void AppendProperty(cmMakefile const* mf,
     const std::string& prop, const char* value,bool asString=false);
 
+  bool HasProperty(const std::string& prop) const;
+
   bool GetProperty(const std::string& prop, std::string& value) const;
 
   bool GetPropertyAsBool(const std::string& prop) const;
 
+  void GetPropertyAsList(const std::string& prop,
+    std::vector<std::string>& list) const;
+
   void SetName(cmMakefile* mf, const std::string& name);
 
   std::string const& GetName() const;
diff --git a/Source/cmListFileCache.cxx b/Source/cmListFileCache.cxx
index 705666d..3fc5b69 100644
--- a/Source/cmListFileCache.cxx
+++ b/Source/cmListFileCache.cxx
@@ -142,7 +142,8 @@
                            bool topLevel,
                            cmMakefile *mf)
 {
-  if(!cmSystemTools::FileExists(filename))
+  if(!cmSystemTools::FileExists(filename) ||
+     cmSystemTools::FileIsDirectory(filename))
     {
     return false;
     }
diff --git a/Source/cmListFileLexer.c b/Source/cmListFileLexer.c
index bfa388e..af4fc3d 100644
--- a/Source/cmListFileLexer.c
+++ b/Source/cmListFileLexer.c
@@ -369,8 +369,8 @@
         *yy_cp = '\0'; \
         yyg->yy_c_buf_p = yy_cp;
 
-#define YY_NUM_RULES 23
-#define YY_END_OF_BUFFER 24
+#define YY_NUM_RULES 24
+#define YY_END_OF_BUFFER 25
 /* This struct is not used in this scanner,
    but its presence is necessary. */
 struct yy_trans_info
@@ -381,10 +381,10 @@
 static yyconst flex_int16_t yy_accept[77] =
     {   0,
         0,    0,    0,    0,    0,    0,    0,    0,    4,    4,
-       24,   13,   21,    1,   15,    3,   13,    5,    6,    7,
-       22,   22,   16,   18,   19,   20,   10,   11,    8,   12,
-        9,    4,   13,    0,   13,    0,   21,    0,    0,    7,
-       13,    0,   13,    0,    2,    0,   13,   16,    0,   17,
+       25,   13,   22,    1,   16,    3,   13,    5,    6,    7,
+       15,   23,   17,   19,   20,   21,   10,   11,    8,   12,
+        9,    4,   13,    0,   13,    0,   22,    0,    0,    7,
+       13,    0,   13,    0,    2,    0,   13,   17,    0,   18,
        10,    8,    4,    0,   14,    0,    0,    0,    0,   14,
         0,    0,   14,    0,    0,    0,    2,   14,    0,    0,
         0,    0,    0,    0,    0,    0
@@ -523,10 +523,10 @@
     } ;
 
 /* Table of booleans, true if rule could match eol. */
-static yyconst flex_int32_t yy_rule_can_match_eol[24] =
+static yyconst flex_int32_t yy_rule_can_match_eol[25] =
     {   0,
-1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0,
-    0, 0, 0, 0,     };
+1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1,
+    0, 0, 0, 0, 0,     };
 
 /* The intent behind this definition is that it'll catch
  * any uses of REJECT which flex missed.
@@ -615,7 +615,7 @@
 
 
 
-#line 621 "cmListFileLexer.c"
+#line 628 "cmListFileLexer.c"
 
 #define INITIAL 0
 #define STRING 1
@@ -850,7 +850,7 @@
 #line 91 "cmListFileLexer.in.l"
 
 
-#line 858 "cmListFileLexer.c"
+#line 865 "cmListFileLexer.c"
 
         if ( !yyg->yy_init )
                 {
@@ -1111,75 +1111,84 @@
 YY_RULE_SETUP
 #line 215 "cmListFileLexer.in.l"
 {
+  lexer->token.type = cmListFileLexer_Token_ArgumentUnquoted;
+  cmListFileLexerSetToken(lexer, yytext, yyleng);
+  lexer->column += yyleng;
+  return 1;
+}
+case 16:
+YY_RULE_SETUP
+#line 222 "cmListFileLexer.in.l"
+{
   lexer->token.type = cmListFileLexer_Token_ArgumentQuoted;
   cmListFileLexerSetToken(lexer, "", 0);
   lexer->column += yyleng;
   BEGIN(STRING);
 }
         YY_BREAK
-case 16:
+case 17:
 YY_RULE_SETUP
-#line 222 "cmListFileLexer.in.l"
+#line 229 "cmListFileLexer.in.l"
 {
   cmListFileLexerAppend(lexer, yytext, yyleng);
   lexer->column += yyleng;
 }
         YY_BREAK
-case 17:
-/* rule 17 can match eol */
+case 18:
+/* rule 18 can match eol */
 YY_RULE_SETUP
-#line 227 "cmListFileLexer.in.l"
+#line 234 "cmListFileLexer.in.l"
 {
   /* Continuation: text is not part of string */
   ++lexer->line;
   lexer->column = 1;
 }
         YY_BREAK
-case 18:
-/* rule 18 can match eol */
+case 19:
+/* rule 19 can match eol */
 YY_RULE_SETUP
-#line 233 "cmListFileLexer.in.l"
+#line 240 "cmListFileLexer.in.l"
 {
   cmListFileLexerAppend(lexer, yytext, yyleng);
   ++lexer->line;
   lexer->column = 1;
 }
         YY_BREAK
-case 19:
+case 20:
 YY_RULE_SETUP
-#line 239 "cmListFileLexer.in.l"
+#line 246 "cmListFileLexer.in.l"
 {
   lexer->column += yyleng;
   BEGIN(INITIAL);
   return 1;
 }
-case 20:
+case 21:
 YY_RULE_SETUP
-#line 245 "cmListFileLexer.in.l"
+#line 252 "cmListFileLexer.in.l"
 {
   cmListFileLexerAppend(lexer, yytext, yyleng);
   lexer->column += yyleng;
 }
         YY_BREAK
 case YY_STATE_EOF(STRING):
-#line 250 "cmListFileLexer.in.l"
+#line 257 "cmListFileLexer.in.l"
 {
   lexer->token.type = cmListFileLexer_Token_BadString;
   BEGIN(INITIAL);
   return 1;
 }
-case 21:
+case 22:
 YY_RULE_SETUP
-#line 256 "cmListFileLexer.in.l"
+#line 263 "cmListFileLexer.in.l"
 {
   lexer->token.type = cmListFileLexer_Token_Space;
   cmListFileLexerSetToken(lexer, yytext, yyleng);
   lexer->column += yyleng;
   return 1;
 }
-case 22:
+case 23:
 YY_RULE_SETUP
-#line 263 "cmListFileLexer.in.l"
+#line 270 "cmListFileLexer.in.l"
 {
   lexer->token.type = cmListFileLexer_Token_BadCharacter;
   cmListFileLexerSetToken(lexer, yytext, yyleng);
@@ -1188,18 +1197,18 @@
 }
 case YY_STATE_EOF(INITIAL):
 case YY_STATE_EOF(COMMENT):
-#line 270 "cmListFileLexer.in.l"
+#line 277 "cmListFileLexer.in.l"
 {
   lexer->token.type = cmListFileLexer_Token_None;
   cmListFileLexerSetToken(lexer, 0, 0);
   return 0;
 }
-case 23:
+case 24:
 YY_RULE_SETUP
-#line 276 "cmListFileLexer.in.l"
+#line 283 "cmListFileLexer.in.l"
 ECHO;
         YY_BREAK
-#line 1220 "cmListFileLexer.c"
+#line 1238 "cmListFileLexer.c"
 
         case YY_END_OF_BUFFER:
                 {
@@ -2320,7 +2329,7 @@
 
 #define YYTABLES_NAME "yytables"
 
-#line 276 "cmListFileLexer.in.l"
+#line 282 "cmListFileLexer.in.l"
 
 
 
diff --git a/Source/cmListFileLexer.in.l b/Source/cmListFileLexer.in.l
index ed4bf6b..a520c72 100644
--- a/Source/cmListFileLexer.in.l
+++ b/Source/cmListFileLexer.in.l
@@ -212,6 +212,13 @@
   return 1;
 }
 
+\[ {
+  lexer->token.type = cmListFileLexer_Token_ArgumentUnquoted;
+  cmListFileLexerSetToken(lexer, yytext, yyleng);
+  lexer->column += yyleng;
+  return 1;
+}
+
 \" {
   lexer->token.type = cmListFileLexer_Token_ArgumentQuoted;
   cmListFileLexerSetToken(lexer, "", 0);
diff --git a/Source/cmLocalGenerator.cxx b/Source/cmLocalGenerator.cxx
index c8c8c79..50e279b 100644
--- a/Source/cmLocalGenerator.cxx
+++ b/Source/cmLocalGenerator.cxx
@@ -681,7 +681,7 @@
         objVector.push_back(ofname);
         this->AddCustomCommandToCreateObject(ofname.c_str(),
                                              llang, *(*i), target);
-        objs += this->Convert(ofname,START_OUTPUT,MAKEFILE);
+        objs += this->Convert(ofname,START_OUTPUT,SHELL);
         objs += " ";
         }
       }
@@ -1287,9 +1287,11 @@
 //----------------------------------------------------------------------------
 std::string
 cmLocalGenerator::ConvertToIncludeReference(std::string const& path,
-                                            OutputFormat format)
+                                            OutputFormat format,
+                                            bool forceFullPaths)
 {
-  return this->ConvertToOutputForExisting(path, START_OUTPUT, format);
+  return this->ConvertToOutputForExisting(
+    path, forceFullPaths? FULL : START_OUTPUT, format);
 }
 
 //----------------------------------------------------------------------------
@@ -1297,6 +1299,7 @@
                                      const std::vector<std::string> &includes,
                                      cmGeneratorTarget* target,
                                      const std::string& lang,
+                                     bool forceFullPaths,
                                      bool forResponseFile,
                                      const std::string& config)
 {
@@ -1401,7 +1404,7 @@
       flagUsed = true;
       }
     std::string includePath =
-      this->ConvertToIncludeReference(*i, shellFormat);
+      this->ConvertToIncludeReference(*i, shellFormat, forceFullPaths);
     if(quotePaths && includePath.size() && includePath[0] != '\"')
       {
       includeFlags << "\"";
@@ -1861,7 +1864,7 @@
                              ((useWatcomQuote) ? WATCOMQUOTE : SHELL);
   bool escapeAllowMakeVars = !forResponseFile;
   cmOStringStream fout;
-  const char* config = this->Makefile->GetDefinition("CMAKE_BUILD_TYPE");
+  std::string config = this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE");
   cmComputeLinkInformation* pcli = tgt.Target->GetLinkInformation(config);
   if(!pcli)
     {
@@ -2229,7 +2232,10 @@
            "does not know the compile flags to use to enable it.";
       this->GetMakefile()->IssueMessage(cmake::FATAL_ERROR, e.str());
       }
-    this->AppendFlags(flags, opt);
+    else
+      {
+      this->AppendFlagEscape(flags, opt);
+      }
     return;
     }
 
@@ -2275,7 +2281,7 @@
 
     if (const char *opt = target->GetMakefile()->GetDefinition(option_flag))
       {
-      this->AppendFlags(flags, opt);
+      this->AppendFlagEscape(flags, opt);
       return;
       }
     }
@@ -2752,7 +2758,7 @@
 {
   std::string result = source;
   // Convert it to an output path.
-  if (output == MAKEFILE)
+  if (output == MAKERULE)
     {
     result = cmSystemTools::ConvertToOutputPath(result.c_str());
     }
@@ -2995,6 +3001,17 @@
 }
 
 //----------------------------------------------------------------------------
+class cmInstallTargetGeneratorLocal: public cmInstallTargetGenerator
+{
+public:
+  cmInstallTargetGeneratorLocal(cmTarget& t, const char* dest, bool implib):
+    cmInstallTargetGenerator(
+      t, dest, implib, "", std::vector<std::string>(), "Unspecified",
+      cmInstallGenerator::SelectMessageLevel(t.GetMakefile()),
+      false) {}
+};
+
+//----------------------------------------------------------------------------
 void
 cmLocalGenerator
 ::GenerateTargetInstallRules(
@@ -3039,7 +3056,8 @@
         case cmTarget::MODULE_LIBRARY:
           {
           // Use a target install generator.
-          cmInstallTargetGenerator g(l->second, destination.c_str(), false);
+          cmInstallTargetGeneratorLocal
+            g(l->second, destination.c_str(), false);
           g.Generate(os, config, configurationTypes);
           }
           break;
@@ -3049,16 +3067,19 @@
           // Special code to handle DLL.  Install the import library
           // to the normal destination and the DLL to the runtime
           // destination.
-          cmInstallTargetGenerator g1(l->second, destination.c_str(), true);
+          cmInstallTargetGeneratorLocal
+            g1(l->second, destination.c_str(), true);
           g1.Generate(os, config, configurationTypes);
           // We also skip over the leading slash given by the user.
           destination = l->second.GetRuntimeInstallPath().substr(1);
           cmSystemTools::ConvertToUnixSlashes(destination);
-          cmInstallTargetGenerator g2(l->second, destination.c_str(), false);
+          cmInstallTargetGeneratorLocal
+            g2(l->second, destination.c_str(), false);
           g2.Generate(os, config, configurationTypes);
 #else
           // Use a target install generator.
-          cmInstallTargetGenerator g(l->second, destination.c_str(), false);
+          cmInstallTargetGeneratorLocal
+            g(l->second, destination.c_str(), false);
           g.Generate(os, config, configurationTypes);
 #endif
           }
diff --git a/Source/cmLocalGenerator.h b/Source/cmLocalGenerator.h
index ad73073..3a9d5be 100644
--- a/Source/cmLocalGenerator.h
+++ b/Source/cmLocalGenerator.h
@@ -106,7 +106,7 @@
    * path setting
    */
   enum RelativeRoot { NONE, FULL, HOME, START, HOME_OUTPUT, START_OUTPUT };
-  enum OutputFormat { UNCHANGED, MAKEFILE, SHELL, WATCOMQUOTE, RESPONSE };
+  enum OutputFormat { UNCHANGED, MAKERULE, SHELL, WATCOMQUOTE, RESPONSE };
   std::string ConvertToOutputFormat(const std::string& source,
                                     OutputFormat output);
   std::string Convert(const std::string& remote, RelativeRoot local,
@@ -160,6 +160,7 @@
   std::string GetIncludeFlags(const std::vector<std::string> &includes,
                               cmGeneratorTarget* target,
                               const std::string& lang,
+                              bool forceFullPaths = false,
                               bool forResponseFile = false,
                               const std::string& config = "");
 
@@ -215,7 +216,8 @@
                                          OutputFormat format = SHELL);
 
   virtual std::string ConvertToIncludeReference(std::string const& path,
-                                                OutputFormat format = SHELL);
+                                                OutputFormat format = SHELL,
+                                                bool forceFullPaths = false);
 
   /** Called from command-line hook to clear dependencies.  */
   virtual void ClearDependencies(cmMakefile* /* mf */,
diff --git a/Source/cmLocalNinjaGenerator.cxx b/Source/cmLocalNinjaGenerator.cxx
index 2ac8363..398b55a 100644
--- a/Source/cmLocalNinjaGenerator.cxx
+++ b/Source/cmLocalNinjaGenerator.cxx
@@ -151,9 +151,10 @@
 
 std::string
 cmLocalNinjaGenerator::ConvertToIncludeReference(std::string const& path,
-                                                 OutputFormat format)
+                                                 OutputFormat format,
+                                                 bool forceFullPaths)
 {
-  return this->Convert(path, HOME_OUTPUT, format);
+  return this->Convert(path, forceFullPaths? FULL : HOME_OUTPUT, format);
 }
 
 //----------------------------------------------------------------------------
@@ -189,6 +190,7 @@
 {
   // For the build file.
   this->WriteProjectHeader(this->GetBuildFileStream());
+  this->WriteNinjaRequiredVersion(this->GetBuildFileStream());
   this->WriteNinjaFilesInclusion(this->GetBuildFileStream());
 
   // For the rule file.
@@ -205,6 +207,30 @@
   cmGlobalNinjaGenerator::WriteDivider(os);
 }
 
+void cmLocalNinjaGenerator::WriteNinjaRequiredVersion(std::ostream& os)
+{
+  // Default required version
+  // Ninja generator uses 'deps' and 'msvc_deps_prefix' introduced in 1.3
+  std::string requiredVersion = "1.3";
+
+  // Ninja generator uses the 'console' pool if available (>= 1.5)
+  std::string usedVersion = this->GetGlobalNinjaGenerator()->ninjaVersion();
+  if(cmSystemTools::VersionCompare(cmSystemTools::OP_LESS,
+                                   usedVersion.c_str(),
+                                   "1.5") ==  false)
+    {
+      requiredVersion = "1.5";
+    }
+
+  cmGlobalNinjaGenerator::WriteComment(os,
+                          "Minimal version of Ninja required by this file");
+  os
+    << "ninja_required_version = "
+    << requiredVersion
+    << std::endl << std::endl
+    ;
+}
+
 void cmLocalNinjaGenerator::WritePools(std::ostream& os)
 {
   cmGlobalNinjaGenerator::WriteDivider(os);
diff --git a/Source/cmLocalNinjaGenerator.h b/Source/cmLocalNinjaGenerator.h
index 11321b8..1d27224 100644
--- a/Source/cmLocalNinjaGenerator.h
+++ b/Source/cmLocalNinjaGenerator.h
@@ -108,7 +108,8 @@
 
 protected:
   virtual std::string ConvertToIncludeReference(std::string const& path,
-                                                OutputFormat format = SHELL);
+                                                OutputFormat format = SHELL,
+                                                bool forceFullPaths = false);
 
 
 private:
@@ -117,6 +118,7 @@
 
   void WriteBuildFileTop();
   void WriteProjectHeader(std::ostream& os);
+  void WriteNinjaRequiredVersion(std::ostream& os);
   void WriteNinjaFilesInclusion(std::ostream& os);
   void WriteProcessedMakefile(std::ostream& os);
   void WritePools(std::ostream& os);
diff --git a/Source/cmLocalUnixMakefileGenerator3.cxx b/Source/cmLocalUnixMakefileGenerator3.cxx
index 94e45e5..23513fa 100644
--- a/Source/cmLocalUnixMakefileGenerator3.cxx
+++ b/Source/cmLocalUnixMakefileGenerator3.cxx
@@ -630,7 +630,7 @@
 
   // Construct the left hand side of the rule.
   replace = target;
-  std::string tgt = this->Convert(replace,HOME_OUTPUT,MAKEFILE);
+  std::string tgt = this->Convert(replace,HOME_OUTPUT,MAKERULE);
   const char* space = "";
   if(tgt.size() == 1)
     {
@@ -663,7 +663,7 @@
         dep != depends.end(); ++dep)
       {
       replace = *dep;
-      replace = this->Convert(replace,HOME_OUTPUT,MAKEFILE);
+      replace = this->Convert(replace,HOME_OUTPUT,MAKERULE);
       os << cmMakeSafe(tgt) << space << ": " << cmMakeSafe(replace) << "\n";
       }
     }
diff --git a/Source/cmLocalVisualStudio6Generator.cxx b/Source/cmLocalVisualStudio6Generator.cxx
index 5db735f..c14fb2b 100644
--- a/Source/cmLocalVisualStudio6Generator.cxx
+++ b/Source/cmLocalVisualStudio6Generator.cxx
@@ -1101,7 +1101,8 @@
       }
     }
   // find link libraries
-  const cmTarget::LinkLibraryVectorType& libs = target.GetLinkLibraries();
+  const cmTarget::LinkLibraryVectorType& libs =
+    target.GetLinkLibrariesForVS6();
   cmTarget::LinkLibraryVectorType::const_iterator j;
   for(j = libs.begin(); j != libs.end(); ++j)
     {
diff --git a/Source/cmLocalVisualStudio7Generator.cxx b/Source/cmLocalVisualStudio7Generator.cxx
index a6c6e8d..eb45423 100644
--- a/Source/cmLocalVisualStudio7Generator.cxx
+++ b/Source/cmLocalVisualStudio7Generator.cxx
@@ -44,11 +44,20 @@
 
 extern cmVS7FlagTable cmLocalVisualStudio7GeneratorFlagTable[];
 
+static void cmConvertToWindowsSlash(std::string& s)
+{
+  std::string::size_type pos = 0;
+  while((pos = s.find('/', pos)) != std::string::npos)
+    {
+    s[pos] = '\\';
+    pos++;
+    }
+}
+
 //----------------------------------------------------------------------------
 cmLocalVisualStudio7Generator::cmLocalVisualStudio7Generator(VSVersion v):
   cmLocalVisualStudioGenerator(v)
 {
-  this->PlatformName = "Win32";
   this->ExtraFlagTable = 0;
   this->Internal = new cmLocalVisualStudio7GeneratorInternals(this);
 }
@@ -647,8 +656,11 @@
     {
     mfcFlag = "0";
     }
+  cmGlobalVisualStudio7Generator* gg =
+    static_cast<cmGlobalVisualStudio7Generator*>(this->GlobalGenerator);
   fout << "\t\t<Configuration\n"
-       << "\t\t\tName=\"" << configName << "|" << this->PlatformName << "\"\n"
+       << "\t\t\tName=\"" << configName
+       << "|" << gg->GetPlatformName() << "\"\n"
        << "\t\t\tOutputDirectory=\"" << configName << "\"\n";
   // This is an internal type to Visual Studio, it seems that:
   // 4 == static library
@@ -784,6 +796,20 @@
        << "\t\t\tUseOfMFC=\"" << mfcFlag << "\"\n"
        << "\t\t\tATLMinimizesCRunTimeLibraryUsage=\"false\"\n";
 
+  if (this->FortranProject)
+    {
+    // Intel Fortran >= 15.0 uses TargetName property.
+    std::string targetNameFull = target.GetFullName(configName);
+    std::string targetName =
+      cmSystemTools::GetFilenameWithoutLastExtension(targetNameFull);
+    std::string targetExt =
+      cmSystemTools::GetFilenameLastExtension(targetNameFull);
+    fout <<
+      "\t\t\tTargetName=\"" << this->EscapeForXML(targetName) << "\"\n"
+      "\t\t\tTargetExt=\"" << this->EscapeForXML(targetExt) << "\"\n"
+      ;
+    }
+
   // If unicode is enabled change the character set to unicode, if not
   // then default to MBCS.
   if(targetOptions.UsingUnicode())
@@ -860,6 +886,31 @@
       }
     }
   fout << "/>\n";  // end of <Tool Name=VCCLCompilerTool
+  if(gg->IsMasmEnabled() && !this->FortranProject)
+    {
+    Options masmOptions(this, Options::MasmCompiler, 0, 0);
+    fout <<
+      "\t\t\t<Tool\n"
+      "\t\t\t\tName=\"MASM\"\n"
+      "\t\t\t\tIncludePaths=\""
+      ;
+    const char* sep = "";
+    for(i = includes.begin(); i != includes.end(); ++i)
+      {
+      std::string inc = *i;
+      cmConvertToWindowsSlash(inc);
+      fout << sep << this->EscapeForXML(inc);
+      sep = ";";
+      }
+    fout << "\"\n";
+    // Use same preprocessor definitions as VCCLCompilerTool.
+    targetOptions.OutputPreprocessorDefinitions(fout, "\t\t\t\t", "\n",
+                                                "ASM_MASM");
+    masmOptions.OutputFlagMap(fout, "\t\t\t\t");
+    fout <<
+      "\t\t\t\tObjectFile=\"$(IntDir)\\\"\n"
+      "\t\t\t/>\n";
+    }
   tool = "VCCustomBuildTool";
   if(this->FortranProject)
     {
@@ -896,11 +947,11 @@
     }
   fout << "\"\n";
   fout << "\t\t\t\tMkTypLibCompatible=\"false\"\n";
-  if( this->PlatformName == "x64" )
+  if( gg->GetPlatformName() == "x64" )
     {
     fout << "\t\t\t\tTargetEnvironment=\"3\"\n";
     }
-  else if( this->PlatformName == "ia64" )
+  else if( gg->GetPlatformName() == "ia64" )
     {
     fout << "\t\t\t\tTargetEnvironment=\"2\"\n";
     }
@@ -1011,7 +1062,7 @@
   if(!this->ModuleDefinitionFile.empty())
     {
     std::string defFile =
-      this->ConvertToXMLOutputPath(this->ModuleDefinitionFile.c_str());
+      this->ConvertToOptionallyRelativeOutputPath(this->ModuleDefinitionFile);
     linkOptions.AddFlag("ModuleDefinitionFile", defFile.c_str());
     }
   switch(target.GetType())
@@ -1640,6 +1691,8 @@
              std::ostream &fout, const std::string& libName,
              std::vector<std::string> *configs)
 {
+  cmGlobalVisualStudio7Generator* gg =
+    static_cast<cmGlobalVisualStudio7Generator *>(this->GlobalGenerator);
   const std::vector<const cmSourceFile *> &sourceFiles =
     sg->GetSourceFiles();
   std::vector<cmSourceGroup> const& children  = sg->GetGroupChildren();
@@ -1691,11 +1744,12 @@
       else if(!fcinfo.FileConfigMap.empty())
         {
         const char* aCompilerTool = "VCCLCompilerTool";
-        const char* lang = "CXX";
+        const char* ppLang = "CXX";
         if(this->FortranProject)
           {
           aCompilerTool = "VFFortranCompilerTool";
           }
+        std::string const& lang = (*sf)->GetLanguage();
         std::string ext = (*sf)->GetExtension();
         ext = cmSystemTools::LowerCase(ext);
         if(ext == "idl")
@@ -1709,7 +1763,7 @@
         if(ext == "rc")
           {
           aCompilerTool = "VCResourceCompilerTool";
-          lang = "RC";
+          ppLang = "RC";
           if(this->FortranProject)
             {
             aCompilerTool = "VFResourceCompilerTool";
@@ -1723,6 +1777,11 @@
             aCompilerTool = "VFCustomBuildTool";
             }
           }
+        if (gg->IsMasmEnabled() && !this->FortranProject &&
+            lang == "ASM_MASM")
+          {
+          aCompilerTool = "MASM";
+          }
         for(std::map<std::string, cmLVS7GFileConfig>::const_iterator
               fci = fcinfo.FileConfigMap.begin();
             fci != fcinfo.FileConfigMap.end(); ++fci)
@@ -1730,7 +1789,7 @@
           cmLVS7GFileConfig const& fc = fci->second;
           fout << "\t\t\t\t<FileConfiguration\n"
                << "\t\t\t\t\tName=\""  << fci->first
-               << "|" << this->PlatformName << "\"";
+               << "|" << gg->GetPlatformName() << "\"";
           if(fc.ExcludedFromBuild)
             {
             fout << " ExcludedFromBuild=\"true\"";
@@ -1759,7 +1818,7 @@
             fileOptions.OutputFlagMap(fout, "\t\t\t\t\t");
             fileOptions.OutputPreprocessorDefinitions(fout,
                                                       "\t\t\t\t\t", "\n",
-                                                      lang);
+                                                      ppLang);
             }
           if(!fc.AdditionalDeps.empty())
             {
@@ -1800,6 +1859,9 @@
                 const cmCustomCommand& command,
                 FCInfo& fcinfo)
 {
+  cmGlobalVisualStudio7Generator* gg =
+    static_cast<cmGlobalVisualStudio7Generator *>(this->GlobalGenerator);
+
   // Write the rule for each configuration.
   std::vector<std::string>::iterator i;
   std::vector<std::string> *configs =
@@ -1820,7 +1882,8 @@
     cmCustomCommandGenerator ccg(command, *i, this->Makefile);
     cmLVS7GFileConfig const& fc = fcinfo.FileConfigMap[*i];
     fout << "\t\t\t\t<FileConfiguration\n";
-    fout << "\t\t\t\t\tName=\"" << *i << "|" << this->PlatformName << "\">\n";
+    fout << "\t\t\t\t\tName=\"" << *i << "|"
+         << gg->GetPlatformName() << "\">\n";
     if(!fc.CompileFlags.empty())
       {
       fout << "\t\t\t\t\t<Tool\n"
@@ -2030,7 +2093,7 @@
   fout<< "\tKeyword=\"" << keyword << "\">\n"
        << "\tProjectGUID=\"{" << gg->GetGUID(libName.c_str()) << "}\">\n"
        << "\t<Platforms>\n"
-       << "\t\t<Platform\n\t\t\tName=\"" << this->PlatformName << "\"/>\n"
+       << "\t\t<Platform\n\t\t\tName=\"" << gg->GetPlatformName() << "\"/>\n"
        << "\t</Platforms>\n";
 }
 
@@ -2085,8 +2148,18 @@
     }
   fout << "\tKeyword=\"" << keyword << "\">\n"
        << "\t<Platforms>\n"
-       << "\t\t<Platform\n\t\t\tName=\"" << this->PlatformName << "\"/>\n"
+       << "\t\t<Platform\n\t\t\tName=\"" << gg->GetPlatformName() << "\"/>\n"
        << "\t</Platforms>\n";
+  if(gg->IsMasmEnabled())
+    {
+    fout <<
+      "\t<ToolFiles>\n"
+      "\t\t<DefaultToolFile\n"
+      "\t\t\tFileName=\"masm.rules\"\n"
+      "\t\t/>\n"
+      "\t</ToolFiles>\n"
+      ;
+    }
 }
 
 
diff --git a/Source/cmLocalVisualStudio7Generator.h b/Source/cmLocalVisualStudio7Generator.h
index 6c04559..c2caa26 100644
--- a/Source/cmLocalVisualStudio7Generator.h
+++ b/Source/cmLocalVisualStudio7Generator.h
@@ -53,8 +53,6 @@
    */
   void SetBuildType(BuildType,const std::string& name);
 
-  void SetPlatformName(const std::string& n) { this->PlatformName = n;}
-
   void SetExtraFlagTable(cmVS7FlagTable const* table)
     { this->ExtraFlagTable = table; }
   virtual std::string GetTargetDirectory(cmTarget const&) const;
@@ -124,7 +122,6 @@
   std::string ModuleDefinitionFile;
   bool FortranProject;
   bool WindowsCEProject;
-  std::string PlatformName; // Win32 or x64
   cmLocalVisualStudio7GeneratorInternals* Internal;
 };
 
diff --git a/Source/cmLocalVisualStudioGenerator.h b/Source/cmLocalVisualStudioGenerator.h
index 3bf4f43..d26c2ea 100644
--- a/Source/cmLocalVisualStudioGenerator.h
+++ b/Source/cmLocalVisualStudioGenerator.h
@@ -40,7 +40,9 @@
     VS9 = 90,
     VS10 = 100,
     VS11 = 110,
-    VS12 = 120
+    VS12 = 120,
+    /* VS13 = 130 was skipped */
+    VS14 = 140
   };
 
   cmLocalVisualStudioGenerator(VSVersion v);
diff --git a/Source/cmMakefile.cxx b/Source/cmMakefile.cxx
index 630957f..0bd1624 100644
--- a/Source/cmMakefile.cxx
+++ b/Source/cmMakefile.cxx
@@ -989,7 +989,7 @@
 
   // Choose a source file on which to store the custom command.
   cmSourceFile* file = 0;
-  if(!main_dependency.empty())
+  if(!commandLines.empty() && !main_dependency.empty())
     {
     // The main dependency was specified.  Use it unless a different
     // custom command already used it.
@@ -1010,11 +1010,9 @@
         file = 0;
         }
       }
-    else
+    else if (!file)
       {
-      // The main dependency does not have a custom command or we are
-      // allowed to replace it.  Use it to store the command.
-      file = this->GetOrCreateSource(main_dependency);
+      file = this->CreateSource(main_dependency);
       }
     }
 
@@ -1041,7 +1039,10 @@
       }
 
     // Create a cmSourceFile for the rule file.
-    file = this->GetOrCreateSource(outName, true);
+    if (!file)
+      {
+      file = this->CreateSource(outName, true);
+      }
     file->SetProperty("__CMAKE_RULE", "1");
     }
 
@@ -1055,16 +1056,16 @@
       }
     }
 
-  // Construct a complete list of dependencies.
-  std::vector<std::string> depends2(depends);
-  if(!main_dependency.empty())
-    {
-    depends2.push_back(main_dependency);
-    }
-
   // Attach the custom command to the file.
   if(file)
     {
+    // Construct a complete list of dependencies.
+    std::vector<std::string> depends2(depends);
+    if(!main_dependency.empty())
+      {
+      depends2.push_back(main_dependency);
+      }
+
     cmCustomCommand* cc =
       new cmCustomCommand(this, outputs, depends2, commandLines,
                           comment, workingDir);
@@ -1256,28 +1257,31 @@
     }
 
   // Store the custom command in the target.
-  std::string force = this->GetStartOutputDirectory();
-  force += cmake::GetCMakeFilesDirectory();
-  force += "/";
-  force += utilityName;
-  std::string no_main_dependency = "";
-  bool no_replace = false;
-  this->AddCustomCommandToOutput(force, depends,
-                                 no_main_dependency,
-                                 commandLines, comment,
-                                 workingDirectory, no_replace,
-                                 escapeOldStyle);
-  cmSourceFile* sf = target->AddSourceCMP0049(force);
+  if (!commandLines.empty() || !depends.empty())
+    {
+    std::string force = this->GetStartOutputDirectory();
+    force += cmake::GetCMakeFilesDirectory();
+    force += "/";
+    force += utilityName;
+    std::string no_main_dependency = "";
+    bool no_replace = false;
+    this->AddCustomCommandToOutput(force, depends,
+                                   no_main_dependency,
+                                   commandLines, comment,
+                                   workingDirectory, no_replace,
+                                   escapeOldStyle);
+    cmSourceFile* sf = target->AddSourceCMP0049(force);
 
-  // The output is not actually created so mark it symbolic.
-  if(sf)
-    {
-    sf->SetProperty("SYMBOLIC", "1");
-    }
-  else
-    {
-    cmSystemTools::Error("Could not get source file entry for ",
-                         force.c_str());
+    // The output is not actually created so mark it symbolic.
+    if(sf)
+      {
+      sf->SetProperty("SYMBOLIC", "1");
+      }
+    else
+      {
+      cmSystemTools::Error("Could not get source file entry for ",
+                          force.c_str());
+      }
     }
   return target;
 }
@@ -3288,6 +3292,7 @@
   this->FunctionBlockerBarriers.pop_back();
 }
 
+//----------------------------------------------------------------------------
 bool cmMakefile::ExpandArguments(
   std::vector<cmListFileArgument> const& inArgs,
   std::vector<std::string>& outArgs) const
@@ -3324,6 +3329,47 @@
 }
 
 //----------------------------------------------------------------------------
+bool cmMakefile::ExpandArguments(
+  std::vector<cmListFileArgument> const& inArgs,
+  std::vector<cmExpandedCommandArgument>& outArgs) const
+{
+  std::vector<cmListFileArgument>::const_iterator i;
+  std::string value;
+  outArgs.reserve(inArgs.size());
+  for(i = inArgs.begin(); i != inArgs.end(); ++i)
+    {
+    // No expansion in a bracket argument.
+    if(i->Delim == cmListFileArgument::Bracket)
+      {
+      outArgs.push_back(cmExpandedCommandArgument(i->Value, true));
+      continue;
+      }
+    // Expand the variables in the argument.
+    value = i->Value;
+    this->ExpandVariablesInString(value, false, false, false,
+                                  i->FilePath, i->Line,
+                                  false, false);
+
+    // If the argument is quoted, it should be one argument.
+    // Otherwise, it may be a list of arguments.
+    if(i->Delim == cmListFileArgument::Quoted)
+      {
+      outArgs.push_back(cmExpandedCommandArgument(value, true));
+      }
+    else
+      {
+      std::vector<std::string> stringArgs;
+      cmSystemTools::ExpandListArgument(value, stringArgs);
+      for(size_t j = 0; j < stringArgs.size(); ++j)
+        {
+        outArgs.push_back(cmExpandedCommandArgument(stringArgs[j], false));
+        }
+      }
+    }
+  return !cmSystemTools::GetFatalErrorOccured();
+}
+
+//----------------------------------------------------------------------------
 void cmMakefile::AddFunctionBlocker(cmFunctionBlocker* fb)
 {
   if(!this->CallStack.empty())
@@ -3451,6 +3497,19 @@
 }
 
 //----------------------------------------------------------------------------
+cmSourceFile* cmMakefile::CreateSource(const std::string& sourceName,
+                                       bool generated)
+{
+  cmSourceFile* sf = new cmSourceFile(this, sourceName);
+  if(generated)
+    {
+    sf->SetProperty("GENERATED", "1");
+    }
+  this->SourceFiles.push_back(sf);
+  return sf;
+}
+
+//----------------------------------------------------------------------------
 cmSourceFile* cmMakefile::GetOrCreateSource(const std::string& sourceName,
                                             bool generated)
 {
@@ -3460,13 +3519,7 @@
     }
   else
     {
-    cmSourceFile* sf = new cmSourceFile(this, sourceName);
-    if(generated)
-      {
-      sf->SetProperty("GENERATED", "1");
-      }
-    this->SourceFiles.push_back(sf);
-    return sf;
+    return this->CreateSource(sourceName, generated);
     }
 }
 
@@ -3499,7 +3552,7 @@
                            const std::string& targetName,
                            bool fast,
                            const std::vector<std::string> *cmakeArgs,
-                           std::string *output)
+                           std::string& output)
 {
   this->Internal->IsSourceFileTryCompile = fast;
   // does the binary directory exist ? If not create it...
@@ -3537,6 +3590,7 @@
   cm.SetHomeOutputDirectory(bindir);
   cm.SetStartDirectory(srcdir);
   cm.SetStartOutputDirectory(bindir);
+  cm.SetGeneratorPlatform(this->GetCMakeInstance()->GetGeneratorPlatform());
   cm.SetGeneratorToolset(this->GetCMakeInstance()->GetGeneratorToolset());
   cm.LoadCache();
   if(!gg->IsMultiConfig())
@@ -4927,12 +4981,14 @@
   this->PolicyBarriers.pop_back();
 }
 
+//----------------------------------------------------------------------------
 bool cmMakefile::SetPolicyVersion(const char *version)
 {
   return this->GetCMakeInstance()->GetPolicies()->
     ApplyPolicyVersion(this,version);
 }
 
+//----------------------------------------------------------------------------
 cmPolicies *cmMakefile::GetPolicies() const
 {
   if (!this->GetCMakeInstance())
@@ -4943,6 +4999,23 @@
 }
 
 //----------------------------------------------------------------------------
+bool cmMakefile::HasCMP0054AlreadyBeenReported(
+  cmListFileContext context) const
+{
+  cmCMP0054Id id(context);
+
+  bool alreadyReported =
+    this->CMP0054ReportedIds.find(id) != this->CMP0054ReportedIds.end();
+
+  if(!alreadyReported)
+    {
+    this->CMP0054ReportedIds.insert(id);
+    }
+
+  return alreadyReported;
+}
+
+//----------------------------------------------------------------------------
 void cmMakefile::RecordPolicies(cmPolicies::PolicyMap& pm)
 {
   /* Record the setting of every policy.  */
diff --git a/Source/cmMakefile.h b/Source/cmMakefile.h
index d5ffd98..164290a 100644
--- a/Source/cmMakefile.h
+++ b/Source/cmMakefile.h
@@ -21,6 +21,7 @@
 #include "cmTarget.h"
 #include "cmNewLineStyle.h"
 #include "cmGeneratorTarget.h"
+#include "cmExpandedCommandArgument.h"
 #include "cmake.h"
 
 #if defined(CMAKE_BUILD_WITH_CMAKE)
@@ -130,7 +131,7 @@
                  const std::string& projectName, const std::string& targetName,
                  bool fast,
                  const std::vector<std::string> *cmakeArgs,
-                 std::string *output);
+                 std::string& output);
 
   bool GetIsSourceFileTryCompile() const;
 
@@ -375,7 +376,35 @@
   /**
     * Get the Policies Instance
     */
- cmPolicies *GetPolicies() const;
+  cmPolicies *GetPolicies() const;
+
+  struct cmCMP0054Id
+  {
+    cmCMP0054Id(cmListFileContext const& context):
+        Context(context)
+    {
+
+    }
+
+    bool operator< (cmCMP0054Id const& id) const
+    {
+      if(this->Context.FilePath != id.Context.FilePath)
+        return this->Context.FilePath < id.Context.FilePath;
+
+      return this->Context.Line < id.Context.Line;
+    }
+
+    cmListFileContext Context;
+  };
+
+  mutable std::set<cmCMP0054Id> CMP0054ReportedIds;
+
+  /**
+   * Determine if the given context, name pair has already been reported
+   * in context of CMP0054.
+   */
+  bool HasCMP0054AlreadyBeenReported(
+    cmListFileContext context) const;
 
   /**
    * Add an auxiliary directory to the build.
@@ -560,6 +589,13 @@
    */
   cmSourceFile* GetSource(const std::string& sourceName) const;
 
+  /** Create the source file and return it. generated
+   * indicates if it is a generated file, this is used in determining
+   * how to create the source file instance e.g. name
+   */
+  cmSourceFile* CreateSource(const std::string& sourceName,
+                             bool generated = false);
+
   /** Get a cmSourceFile pointer for a given source name, if the name is
    *  not found, then create the source file and return it. generated
    * indicates if it is a generated file, this is used in determining
@@ -763,6 +799,10 @@
    */
   bool ExpandArguments(std::vector<cmListFileArgument> const& inArgs,
                        std::vector<std::string>& outArgs) const;
+
+  bool ExpandArguments(std::vector<cmListFileArgument> const& inArgs,
+                       std::vector<cmExpandedCommandArgument>& outArgs) const;
+
   /**
    * Get the instance
    */
diff --git a/Source/cmMakefileTargetGenerator.cxx b/Source/cmMakefileTargetGenerator.cxx
index 403f6e6..1f8f686 100644
--- a/Source/cmMakefileTargetGenerator.cxx
+++ b/Source/cmMakefileTargetGenerator.cxx
@@ -218,7 +218,7 @@
     << this->LocalGenerator->IncludeDirective << " " << root
     << this->Convert(dependFileNameFull,
                      cmLocalGenerator::HOME_OUTPUT,
-                     cmLocalGenerator::MAKEFILE)
+                     cmLocalGenerator::MAKERULE)
     << "\n\n";
 
   if(!this->NoRuleMessages)
@@ -229,7 +229,7 @@
       << this->LocalGenerator->IncludeDirective << " " << root
       << this->Convert(this->ProgressFileNameFull,
                        cmLocalGenerator::HOME_OUTPUT,
-                       cmLocalGenerator::MAKEFILE)
+                       cmLocalGenerator::MAKERULE)
       << "\n\n";
     }
 
@@ -262,7 +262,7 @@
     << this->LocalGenerator->IncludeDirective << " " << root
     << this->Convert(this->FlagFileNameFull,
                                      cmLocalGenerator::HOME_OUTPUT,
-                                     cmLocalGenerator::MAKEFILE)
+                                     cmLocalGenerator::MAKERULE)
     << "\n\n";
 }
 
@@ -361,9 +361,13 @@
   for(std::set<std::string>::const_iterator l = languages.begin();
       l != languages.end(); ++l)
     {
-    *this->FlagFileStream << *l << "_FLAGS = " << this->GetFlags(*l) << "\n\n";
-    *this->FlagFileStream << *l << "_DEFINES = " << this->GetDefines(*l) <<
-      "\n\n";
+    std::string flags = this->GetFlags(*l);
+    std::string defines = this->GetDefines(*l);
+    // Escape comment characters so they do not terminate assignment.
+    cmSystemTools::ReplaceString(flags, "#", "\\#");
+    cmSystemTools::ReplaceString(defines, "#", "\\#");
+    *this->FlagFileStream << *l << "_FLAGS = " << flags << "\n\n";
+    *this->FlagFileStream << *l << "_DEFINES = " << defines << "\n\n";
     }
 }
 
@@ -1958,7 +1962,7 @@
 
   std::string includeFlags =
     this->LocalGenerator->GetIncludeFlags(includes, this->GeneratorTarget,
-                                          lang, useResponseFile);
+                                          lang, false, useResponseFile);
   if(includeFlags.empty())
     {
     return;
diff --git a/Source/cmMakefileUtilityTargetGenerator.cxx b/Source/cmMakefileUtilityTargetGenerator.cxx
index 6b039bb..617214f 100644
--- a/Source/cmMakefileUtilityTargetGenerator.cxx
+++ b/Source/cmMakefileUtilityTargetGenerator.cxx
@@ -54,7 +54,7 @@
       << this->LocalGenerator->IncludeDirective << " " << root
       << this->Convert(this->ProgressFileNameFull,
                        cmLocalGenerator::HOME_OUTPUT,
-                       cmLocalGenerator::MAKEFILE)
+                       cmLocalGenerator::MAKERULE)
       << "\n\n";
     }
 
diff --git a/Source/cmNinjaNormalTargetGenerator.cxx b/Source/cmNinjaNormalTargetGenerator.cxx
index cfcf9f4..e344df4 100644
--- a/Source/cmNinjaNormalTargetGenerator.cxx
+++ b/Source/cmNinjaNormalTargetGenerator.cxx
@@ -187,12 +187,7 @@
         responseFlag += rspfile;
 
         // build response file content
-        std::string linkOptionVar = cmakeVarLang;
-        linkOptionVar += "_COMPILER_LINKER_OPTION_FLAG_";
-        linkOptionVar += cmTarget::GetTargetTypeName(targetType);
-        const std::string linkOption =
-                GetMakefile()->GetSafeDefinition(linkOptionVar);
-        rspcontent = "$in_newline "+linkOption+" $LINK_PATH $LINK_LIBRARIES";
+        rspcontent = "$in_newline $LINK_PATH $LINK_LIBRARIES";
         vars.Objects = responseFlag.c_str();
         vars.LinkLibraries = "";
     }
@@ -608,6 +603,11 @@
       std::string(cmake::GetCMakeFilesDirectoryPostSlash())
       + target.GetName() + ".rsp";
 
+  // Gather order-only dependencies.
+  cmNinjaDeps orderOnlyDeps;
+  this->GetLocalGenerator()->AppendTargetDepends(this->GetTarget(),
+    orderOnlyDeps);
+
   // Write the build statement for this target.
   globalGen.WriteBuild(this->GetBuildFileStream(),
                         comment.str(),
@@ -615,7 +615,7 @@
                         outputs,
                         explicitDeps,
                         implicitDeps,
-                        emptyDeps,
+                        orderOnlyDeps,
                         vars,
                         rspfile,
                         commandLineLengthLimit);
diff --git a/Source/cmNinjaTargetGenerator.cxx b/Source/cmNinjaTargetGenerator.cxx
index 24689fb..816e6d8 100644
--- a/Source/cmNinjaTargetGenerator.cxx
+++ b/Source/cmNinjaTargetGenerator.cxx
@@ -542,22 +542,24 @@
                    std::back_inserter(orderOnlyDeps), MapToNinjaPath());
     }
 
-  cmNinjaDeps orderOnlyTarget;
-  orderOnlyTarget.push_back(this->OrderDependsTargetForTarget());
-  this->GetGlobalGenerator()->WritePhonyBuild(this->GetBuildFileStream(),
-                                          "Order-only phony target for "
-                                            + this->GetTargetName(),
-                                          orderOnlyTarget,
-                                          cmNinjaDeps(),
-                                          cmNinjaDeps(),
-                                          orderOnlyDeps);
-
+  if (!orderOnlyDeps.empty())
+    {
+    cmNinjaDeps orderOnlyTarget;
+    orderOnlyTarget.push_back(this->OrderDependsTargetForTarget());
+    this->GetGlobalGenerator()->WritePhonyBuild(this->GetBuildFileStream(),
+                                                "Order-only phony target for "
+                                                  + this->GetTargetName(),
+                                                orderOnlyTarget,
+                                                cmNinjaDeps(),
+                                                cmNinjaDeps(),
+                                                orderOnlyDeps);
+    }
   std::vector<cmSourceFile const*> objectSources;
   this->GeneratorTarget->GetObjectSources(objectSources, config);
   for(std::vector<cmSourceFile const*>::const_iterator
         si = objectSources.begin(); si != objectSources.end(); ++si)
     {
-    this->WriteObjectBuildStatement(*si);
+    this->WriteObjectBuildStatement(*si, !orderOnlyDeps.empty());
     }
   std::string def = this->GeneratorTarget->GetModuleDefinitionFile(config);
   if(!def.empty())
@@ -570,7 +572,8 @@
 
 void
 cmNinjaTargetGenerator
-::WriteObjectBuildStatement(cmSourceFile const* source)
+::WriteObjectBuildStatement(
+  cmSourceFile const* source, bool writeOrderDependsTargetForTarget)
 {
   std::string comment;
   const std::string language = source->GetLanguage();
@@ -599,7 +602,10 @@
   }
 
   cmNinjaDeps orderOnlyDeps;
-  orderOnlyDeps.push_back(this->OrderDependsTargetForTarget());
+  if (writeOrderDependsTargetForTarget)
+    {
+    orderOnlyDeps.push_back(this->OrderDependsTargetForTarget());
+    }
 
   // If the source file is GENERATED and does not have a custom command
   // (either attached to this source file or another one), assume that one of
diff --git a/Source/cmNinjaTargetGenerator.h b/Source/cmNinjaTargetGenerator.h
index 94c420f..40a15a3 100644
--- a/Source/cmNinjaTargetGenerator.h
+++ b/Source/cmNinjaTargetGenerator.h
@@ -114,7 +114,8 @@
   void WriteLanguageRules(const std::string& language);
   void WriteCompileRule(const std::string& language);
   void WriteObjectBuildStatements();
-  void WriteObjectBuildStatement(cmSourceFile const* source);
+  void WriteObjectBuildStatement(cmSourceFile const* source,
+                                 bool writeOrderDependsTargetForTarget);
   void WriteCustomCommandBuildStatement(cmCustomCommand *cc);
 
   cmNinjaDeps GetObjects() const
diff --git a/Source/cmOrderDirectories.cxx b/Source/cmOrderDirectories.cxx
index ec671fc..007364c 100644
--- a/Source/cmOrderDirectories.cxx
+++ b/Source/cmOrderDirectories.cxx
@@ -39,8 +39,8 @@
 
     if(file.rfind(".framework") != std::string::npos)
       {
-      cmsys::RegularExpression splitFramework;
-      splitFramework.compile("^(.*)/(.*).framework/(.*)$");
+      static cmsys::RegularExpression
+        splitFramework("^(.*)/(.*).framework/(.*)$");
       if(splitFramework.find(file) &&
         (std::string::npos !=
          splitFramework.match(3).find(splitFramework.match(2))))
@@ -72,7 +72,10 @@
       {
       // Check if this directory conflicts with the entry.
       std::string const& dir = this->OD->OriginalDirectories[i];
-      if(dir != this->Directory && this->FindConflict(dir))
+      if(dir != this->Directory &&
+         cmSystemTools::GetRealPath(dir) !=
+         cmSystemTools::GetRealPath(this->Directory) &&
+         this->FindConflict(dir))
         {
         // The library will be found in this directory but this is not
         // the directory named for it.  Add an entry to make sure the
@@ -90,7 +93,10 @@
       {
       // Check if this directory conflicts with the entry.
       std::string const& dir = this->OD->OriginalDirectories[i];
-      if(dir != this->Directory && this->FindConflict(dir))
+      if(dir != this->Directory &&
+         cmSystemTools::GetRealPath(dir) !=
+         cmSystemTools::GetRealPath(this->Directory) &&
+         this->FindConflict(dir))
         {
         // The library will be found in this directory but it is
         // supposed to be found in an implicit search directory.
@@ -326,8 +332,8 @@
 
       if(fullPath.rfind(".framework") != std::string::npos)
         {
-        cmsys::RegularExpression splitFramework;
-        splitFramework.compile("^(.*)/(.*).framework/(.*)$");
+        static cmsys::RegularExpression
+          splitFramework("^(.*)/(.*).framework/(.*)$");
         if(splitFramework.find(fullPath) &&
           (std::string::npos !=
            splitFramework.match(3).find(splitFramework.match(2))))
diff --git a/Source/cmPolicies.cxx b/Source/cmPolicies.cxx
index 693945d..a420f59 100644
--- a/Source/cmPolicies.cxx
+++ b/Source/cmPolicies.cxx
@@ -359,6 +359,11 @@
     CMP0053, "CMP0053",
     "Simplify variable reference and escape sequence evaluation.",
     3,1,0, cmPolicies::WARN);
+
+  this->DefinePolicy(
+    CMP0054, "CMP0054",
+    "Only interpret if() arguments as variables or keywords when unquoted.",
+    3,1,0, cmPolicies::WARN);
 }
 
 cmPolicies::~cmPolicies()
diff --git a/Source/cmPolicies.h b/Source/cmPolicies.h
index 5d69d14..7c73da8 100644
--- a/Source/cmPolicies.h
+++ b/Source/cmPolicies.h
@@ -109,6 +109,8 @@
     /// INTERFACE_INCLUDE_DIRECTORIES
 
     CMP0053, ///< Simplify variable reference and escape sequence evaluation
+    CMP0054, ///< Only interpret if() arguments as variables
+    /// or keywords when unquoted.
 
     /** \brief Always the last entry.
      *
diff --git a/Source/cmQtAutoGenerators.cxx b/Source/cmQtAutoGenerators.cxx
index cc6932d..93ebde6 100644
--- a/Source/cmQtAutoGenerators.cxx
+++ b/Source/cmQtAutoGenerators.cxx
@@ -392,7 +392,8 @@
   std::map<std::string, std::string> configUicOptions;
 
   if (target->GetPropertyAsBool("AUTOMOC")
-      || target->GetPropertyAsBool("AUTOUIC"))
+      || target->GetPropertyAsBool("AUTOUIC")
+      || target->GetPropertyAsBool("AUTORCC"))
     {
     this->SetupSourceFiles(target);
     }
@@ -1000,6 +1001,7 @@
 
   this->WriteOldMocDefinitionsFile(targetDirectory);
 
+  delete gg->GetCurrentLocalGenerator();
   delete gg;
   gg = NULL;
   makefile = NULL;
@@ -1178,9 +1180,9 @@
   cmSystemTools::ConvertToUnixSlashes(filename);
   filename += "/AutomocOldMocDefinitions.cmake";
 
-  std::fstream outfile;
+  cmsys::ofstream outfile;
   outfile.open(filename.c_str(),
-               std::ios::out | std::ios::trunc);
+               std::ios::trunc);
   outfile << "set(AM_OLD_COMPILE_SETTINGS "
               << cmLocalGenerator::EscapeForCMake(
                  this->CurrentCompileSettingsStr) << ")\n";
@@ -1303,8 +1305,8 @@
   const std::vector<std::string>& headerExtensions =
                                                makefile->GetHeaderExtensions();
 
-  std::map<std::string, std::string> includedUis;
-  std::map<std::string, std::string> skippedUis;
+  std::map<std::string, std::vector<std::string> > includedUis;
+  std::map<std::string, std::vector<std::string> > skippedUis;
   std::vector<std::string> uicSkipped;
   cmSystemTools::ExpandListArgument(this->SkipUic, uicSkipped);
 
@@ -1314,7 +1316,7 @@
     {
     const bool skipUic = std::find(uicSkipped.begin(), uicSkipped.end(), *it)
         != uicSkipped.end();
-    std::map<std::string, std::string>& uiFiles
+    std::map<std::string, std::vector<std::string> >& uiFiles
                                           = skipUic ? skippedUis : includedUis;
     const std::string &absFilename = *it;
     if (this->Verbose)
@@ -1375,12 +1377,17 @@
     {
     this->GenerateMoc(it->first, it->second);
     }
-  for(std::map<std::string, std::string>::const_iterator
+  for(std::map<std::string, std::vector<std::string> >::const_iterator
       it = includedUis.begin();
       it != includedUis.end();
       ++it)
     {
-    this->GenerateUi(it->first, it->second);
+    for (std::vector<std::string>::const_iterator nit = it->second.begin();
+        nit != it->second.end();
+        ++nit)
+      {
+      this->GenerateUi(it->first, *nit);
+      }
     }
 
   if(!this->RccExecutable.empty())
@@ -1444,9 +1451,9 @@
     }
 
   // source file that includes all remaining moc files (_automoc.cpp file)
-  std::fstream outfile;
+  cmsys::ofstream outfile;
   outfile.open(this->OutMocCppFilename.c_str(),
-               std::ios::out | std::ios::trunc);
+               std::ios::trunc);
   outfile << automocSource;
   outfile.close();
 
@@ -1455,9 +1462,9 @@
 
 
 void cmQtAutoGenerators::ParseCppFile(const std::string& absFilename,
-                              const std::vector<std::string>& headerExtensions,
-                              std::map<std::string, std::string>& includedMocs,
-                              std::map<std::string, std::string> &includedUis)
+                const std::vector<std::string>& headerExtensions,
+                std::map<std::string, std::string>& includedMocs,
+                std::map<std::string, std::vector<std::string> > &includedUis)
 {
   cmsys::RegularExpression mocIncludeRegExp(
               "[\n][ \t]*#[ \t]*include[ \t]+"
@@ -1643,9 +1650,9 @@
 
 
 void cmQtAutoGenerators::StrictParseCppFile(const std::string& absFilename,
-                              const std::vector<std::string>& headerExtensions,
-                              std::map<std::string, std::string>& includedMocs,
-                              std::map<std::string, std::string>& includedUis)
+                const std::vector<std::string>& headerExtensions,
+                std::map<std::string, std::string>& includedMocs,
+                std::map<std::string, std::vector<std::string> >& includedUis)
 {
   cmsys::RegularExpression mocIncludeRegExp(
               "[\n][ \t]*#[ \t]*include[ \t]+"
@@ -1763,7 +1770,7 @@
 
 
 void cmQtAutoGenerators::ParseForUic(const std::string& absFilename,
-                              std::map<std::string, std::string>& includedUis)
+                std::map<std::string, std::vector<std::string> >& includedUis)
 {
   if (this->UicExecutable.empty())
     {
@@ -1781,8 +1788,8 @@
 
 
 void cmQtAutoGenerators::ParseForUic(const std::string& absFilename,
-                                     const std::string& contentsString,
-                              std::map<std::string, std::string>& includedUis)
+                const std::string& contentsString,
+                std::map<std::string, std::vector<std::string> >& includedUis)
 {
   if (this->UicExecutable.empty())
     {
@@ -1812,7 +1819,7 @@
       // finding the correct header, so we need to remove the ui_ part
       basename = basename.substr(3);
 
-      includedUis[realName] = basename;
+      includedUis[realName].push_back(basename);
 
       matchOffset += uiIncludeRegExp.end();
       } while(uiIncludeRegExp.find(contentsString.c_str() + matchOffset));
@@ -1858,9 +1865,9 @@
 
 
 void cmQtAutoGenerators::ParseHeaders(const std::set<std::string>& absHeaders,
-                        const std::map<std::string, std::string>& includedMocs,
-                        std::map<std::string, std::string>& notIncludedMocs,
-                        std::map<std::string, std::string>& includedUis)
+                const std::map<std::string, std::string>& includedMocs,
+                std::map<std::string, std::string>& notIncludedMocs,
+                std::map<std::string, std::vector<std::string> >& includedUis)
 {
   for(std::set<std::string>::const_iterator hIt=absHeaders.begin();
       hIt!=absHeaders.end();
diff --git a/Source/cmQtAutoGenerators.h b/Source/cmQtAutoGenerators.h
index 501e13a..c298f5d 100644
--- a/Source/cmQtAutoGenerators.h
+++ b/Source/cmQtAutoGenerators.h
@@ -51,28 +51,28 @@
   bool GenerateUi(const std::string& realName, const std::string& uiFileName);
   bool GenerateQrc();
   void ParseCppFile(const std::string& absFilename,
-                    const std::vector<std::string>& headerExtensions,
-                    std::map<std::string, std::string>& includedMocs,
-                          std::map<std::string, std::string>& includedUis);
+              const std::vector<std::string>& headerExtensions,
+              std::map<std::string, std::string>& includedMocs,
+              std::map<std::string, std::vector<std::string> >& includedUis);
   void StrictParseCppFile(const std::string& absFilename,
-                          const std::vector<std::string>& headerExtensions,
-                          std::map<std::string, std::string>& includedMocs,
-                          std::map<std::string, std::string>& includedUis);
+              const std::vector<std::string>& headerExtensions,
+              std::map<std::string, std::string>& includedMocs,
+              std::map<std::string, std::vector<std::string> >& includedUis);
   void SearchHeadersForCppFile(const std::string& absFilename,
                               const std::vector<std::string>& headerExtensions,
                               std::set<std::string>& absHeaders);
 
   void ParseHeaders(const std::set<std::string>& absHeaders,
-                    const std::map<std::string, std::string>& includedMocs,
-                    std::map<std::string, std::string>& notIncludedMocs,
-                          std::map<std::string, std::string>& includedUis);
+              const std::map<std::string, std::string>& includedMocs,
+              std::map<std::string, std::string>& notIncludedMocs,
+              std::map<std::string, std::vector<std::string> >& includedUis);
 
   void ParseForUic(const std::string& fileName,
-                   const std::string& contentsString,
-                   std::map<std::string, std::string>& includedUis);
+              const std::string& contentsString,
+              std::map<std::string, std::vector<std::string> >& includedUis);
 
   void ParseForUic(const std::string& fileName,
-                   std::map<std::string, std::string>& includedUis);
+              std::map<std::string, std::vector<std::string> >& includedUis);
 
   void Init();
 
diff --git a/Source/cmStandardIncludes.h b/Source/cmStandardIncludes.h
index 3731502..8baf7b3 100644
--- a/Source/cmStandardIncludes.h
+++ b/Source/cmStandardIncludes.h
@@ -462,12 +462,6 @@
     return strcmp(input, m_test.c_str()) == 0;
   }
 
-  // For use with binary_search
-  bool operator()(const char *str1, const char *str2) const
-  {
-    return strcmp(str1, str2) < 0;
-  }
-
 private:
   const std::string m_test;
 };
diff --git a/Source/cmStringCommand.cxx b/Source/cmStringCommand.cxx
index 65912da..90a8f85 100644
--- a/Source/cmStringCommand.cxx
+++ b/Source/cmStringCommand.cxx
@@ -20,6 +20,7 @@
 #include <time.h>
 
 #include <cmTimestamp.h>
+#include <cmUuid.h>
 
 //----------------------------------------------------------------------------
 bool cmStringCommand
@@ -105,6 +106,10 @@
     {
     return this->HandleGenexStripCommand(args);
     }
+  else if(subCommand == "UUID")
+    {
+    return this->HandleUuidCommand(args);
+    }
 
   std::string e = "does not recognize sub-command "+subCommand;
   this->SetError(e);
@@ -981,3 +986,114 @@
 
   return true;
 }
+
+bool cmStringCommand
+::HandleUuidCommand(std::vector<std::string> const& args)
+{
+#if defined(CMAKE_BUILD_WITH_CMAKE)
+  unsigned int argsIndex = 1;
+
+  if(args.size() < 2)
+    {
+    this->SetError("UUID sub-command requires an output variable.");
+    return false;
+    }
+
+  const std::string &outputVariable = args[argsIndex++];
+
+  std::string uuidNamespaceString;
+  std::string uuidName;
+  std::string uuidType;
+  bool uuidUpperCase = false;
+
+  while(args.size() > argsIndex)
+    {
+    if(args[argsIndex] == "NAMESPACE")
+      {
+      ++argsIndex;
+      if(argsIndex >= args.size())
+        {
+        this->SetError("UUID sub-command, NAMESPACE requires a value.");
+        return false;
+        }
+      uuidNamespaceString = args[argsIndex++];
+      }
+    else if(args[argsIndex] == "NAME")
+      {
+      ++argsIndex;
+      if(argsIndex >= args.size())
+        {
+        this->SetError("UUID sub-command, NAME requires a value.");
+        return false;
+        }
+      uuidName = args[argsIndex++];
+      }
+    else if(args[argsIndex] == "TYPE")
+      {
+      ++argsIndex;
+      if(argsIndex >= args.size())
+        {
+        this->SetError("UUID sub-command, TYPE requires a value.");
+        return false;
+        }
+      uuidType = args[argsIndex++];
+      }
+    else if(args[argsIndex] == "UPPER")
+      {
+      ++argsIndex;
+      uuidUpperCase = true;
+      }
+    else
+      {
+      std::string e = "UUID sub-command does not recognize option " +
+          args[argsIndex] + ".";
+      this->SetError(e);
+      return false;
+      }
+    }
+
+  std::string uuid;
+  cmUuid uuidGenerator;
+
+  std::vector<unsigned char> uuidNamespace;
+  if(!uuidGenerator.StringToBinary(uuidNamespaceString, uuidNamespace))
+    {
+    this->SetError("UUID sub-command, malformed NAMESPACE UUID.");
+    return false;
+    }
+
+  if(uuidType == "MD5")
+    {
+    uuid = uuidGenerator.FromMd5(uuidNamespace, uuidName);
+    }
+  else if(uuidType == "SHA1")
+    {
+    uuid = uuidGenerator.FromSha1(uuidNamespace, uuidName);
+    }
+  else
+    {
+    std::string e = "UUID sub-command, unknown TYPE '" + uuidType + "'.";
+    this->SetError(e);
+    return false;
+    }
+
+  if(uuid.empty())
+    {
+    this->SetError("UUID sub-command, generation failed.");
+    return false;
+    }
+
+  if(uuidUpperCase)
+    {
+    uuid = cmSystemTools::UpperCase(uuid);
+    }
+
+  this->Makefile->AddDefinition(outputVariable, uuid.c_str());
+  return true;
+#else
+  cmOStringStream e;
+  e << args[0] << " not available during bootstrap";
+  this->SetError(e.str().c_str());
+  return false;
+#endif
+}
diff --git a/Source/cmStringCommand.h b/Source/cmStringCommand.h
index 8292e64..9c75095 100644
--- a/Source/cmStringCommand.h
+++ b/Source/cmStringCommand.h
@@ -74,6 +74,7 @@
   bool HandleTimestampCommand(std::vector<std::string> const& args);
   bool HandleMakeCIdentifierCommand(std::vector<std::string> const& args);
   bool HandleGenexStripCommand(std::vector<std::string> const& args);
+  bool HandleUuidCommand(std::vector<std::string> const& args);
 
   class RegexReplacement
   {
diff --git a/Source/cmSystemTools.cxx b/Source/cmSystemTools.cxx
index 2e417cb..fbb4416 100644
--- a/Source/cmSystemTools.cxx
+++ b/Source/cmSystemTools.cxx
@@ -91,6 +91,31 @@
 # endif
 #endif
 
+#if defined(CMAKE_BUILD_WITH_CMAKE)
+static std::string
+cm_archive_entry_pathname(struct archive_entry *entry)
+{
+#if cmsys_STL_HAS_WSTRING
+  return cmsys::Encoding::ToNarrow(
+    archive_entry_pathname_w(entry)).c_str();
+#else
+  return archive_entry_pathname(entry);
+#endif
+}
+
+static int cm_archive_read_open_file(struct archive* a,
+                                     const char* file,
+                                     int block_size)
+{
+#if cmsys_STL_HAS_WSTRING
+  std::wstring wfile = cmsys::Encoding::ToWide(file);
+  return archive_read_open_filename_w(a, wfile.c_str(), block_size);
+#else
+  return archive_read_open_filename(a, file, block_size);
+#endif
+}
+#endif
+
 #ifdef _WIN32
 class cmSystemToolsWindowsHandle
 {
@@ -359,14 +384,28 @@
     {
     return false;
     }
-  std::basic_string<char> v = val;
+  size_t len = strlen(val);
+  if (len > 4)
+    {
+    return false;
+    }
+  std::basic_string<char> v(val, len);
 
+  static std::set<std::string> onValues;
+  if(onValues.empty())
+    {
+    onValues.insert("ON");
+    onValues.insert("1");
+    onValues.insert("YES");
+    onValues.insert("TRUE");
+    onValues.insert("Y");
+    }
   for(std::basic_string<char>::iterator c = v.begin();
       c != v.end(); c++)
     {
     *c = static_cast<char>(toupper(*c));
     }
-  return (v == "ON" || v == "1" || v == "YES" || v == "TRUE" || v == "Y");
+  return (onValues.count(v) > 0);
 }
 
 bool cmSystemTools::IsNOTFOUND(const char* val)
@@ -381,19 +420,35 @@
 
 bool cmSystemTools::IsOff(const char* val)
 {
-  if (!val || strlen(val) == 0)
+  if (!val || !*val)
     {
     return true;
     }
-  std::basic_string<char> v = val;
+  size_t len = strlen(val);
+  // Try and avoid toupper() for large strings.
+  if (len > 6)
+    {
+    return cmSystemTools::IsNOTFOUND(val);
+    }
 
+  static std::set<std::string> offValues;
+  if(offValues.empty())
+    {
+    offValues.insert("OFF");
+    offValues.insert("0");
+    offValues.insert("NO");
+    offValues.insert("FALSE");
+    offValues.insert("N");
+    offValues.insert("IGNORE");
+    }
+  // Try and avoid toupper().
+  std::basic_string<char> v(val, len);
   for(std::basic_string<char>::iterator c = v.begin();
       c != v.end(); c++)
     {
     *c = static_cast<char>(toupper(*c));
     }
-  return (v == "OFF" || v == "0" || v == "NO" || v == "FALSE" ||
-          v == "N" || cmSystemTools::IsNOTFOUND(v.c_str()) || v == "IGNORE");
+  return (offValues.count(v) > 0);
 }
 
 //----------------------------------------------------------------------------
@@ -439,7 +494,7 @@
       {
       arg.append(backslashes, '\\');
       backslashes = 0;
-      if(isspace(*c))
+      if(((*c & 0x80) == 0 ) && isspace(*c))
         {
         if(in_quotes)
           {
@@ -1581,7 +1636,7 @@
     }
   strftime(tmp, sizeof(tmp), fmt, localtime(&tim));
   fprintf(out, " %s ", tmp);
-  fprintf(out, "%s", archive_entry_pathname(entry));
+  fprintf(out, "%s", cm_archive_entry_pathname(entry).c_str());
 
   /* Extra information for links. */
   if (archive_entry_hardlink(entry)) /* Hard link */
@@ -1641,11 +1696,13 @@
   archive_read_support_compression_all(a);
   archive_read_support_format_all(a);
   struct archive_entry *entry;
-  int r = archive_read_open_file(a, outFileName, 10240);
+  int r = cm_archive_read_open_file(a, outFileName, 10240);
   if(r)
     {
     cmSystemTools::Error("Problem with archive_read_open_file(): ",
                          archive_error_string(a));
+    archive_write_free(ext);
+    archive_read_close(a);
     return false;
     }
   for (;;)
@@ -1666,7 +1723,7 @@
       if(extract)
         {
         cmSystemTools::Stdout("x ");
-        cmSystemTools::Stdout(archive_entry_pathname(entry));
+        cmSystemTools::Stdout(cm_archive_entry_pathname(entry).c_str());
         }
       else
         {
@@ -1676,7 +1733,7 @@
       }
     else if(!extract)
       {
-      cmSystemTools::Stdout(archive_entry_pathname(entry));
+      cmSystemTools::Stdout(cm_archive_entry_pathname(entry).c_str());
       cmSystemTools::Stdout("\n");
       }
     if(extract)
@@ -1706,7 +1763,8 @@
       else if(const char* linktext = archive_entry_symlink(entry))
         {
         std::cerr << "cmake -E tar: warning: skipping symbolic link \""
-                  << archive_entry_pathname(entry) << "\" -> \""
+                  << cm_archive_entry_pathname(entry)
+                  << "\" -> \""
                   << linktext << "\"." << std::endl;
         }
 #endif
@@ -1715,11 +1773,12 @@
         cmSystemTools::Error("Problem with archive_write_header(): ",
                              archive_error_string(ext));
         cmSystemTools::Error("Current file: ",
-                             archive_entry_pathname(entry));
+                             cm_archive_entry_pathname(entry).c_str());
         break;
         }
       }
     }
+  archive_write_free(ext);
   archive_read_close(a);
   archive_read_finish(a);
   return r == ARCHIVE_EOF || r == ARCHIVE_OK;
@@ -2129,6 +2188,11 @@
   cmSystemToolsCMakeCommand = exe_dir;
   cmSystemToolsCMakeCommand += "/cmake";
   cmSystemToolsCMakeCommand += cmSystemTools::GetExecutableExtension();
+#ifndef CMAKE_BUILD_WITH_CMAKE
+  // The bootstrap cmake does not provide the other tools,
+  // so use the directory where they are about to be built.
+  exe_dir = CMAKE_BOOTSTRAP_BINARY_DIR "/bin";
+#endif
   cmSystemToolsCTestCommand = exe_dir;
   cmSystemToolsCTestCommand += "/ctest";
   cmSystemToolsCTestCommand += cmSystemTools::GetExecutableExtension();
@@ -2181,7 +2245,7 @@
     }
 #else
   // Bootstrap build knows its source.
-  cmSystemToolsCMakeRoot = CMAKE_ROOT_DIR;
+  cmSystemToolsCMakeRoot = CMAKE_BOOTSTRAP_SOURCE_DIR;
 #endif
 }
 
diff --git a/Source/cmTarget.cxx b/Source/cmTarget.cxx
index 59cc14c..b476a27 100644
--- a/Source/cmTarget.cxx
+++ b/Source/cmTarget.cxx
@@ -25,6 +25,12 @@
 #include <stdlib.h> // required for atof
 #include <assert.h>
 #include <errno.h>
+#if defined(CMAKE_BUILD_WITH_CMAKE)
+#include <cmsys/hash_set.hxx>
+#define UNORDERED_SET cmsys::hash_set
+#else
+#define UNORDERED_SET std::set
+#endif
 
 const char* cmTarget::GetTargetTypeName(TargetType targetType)
 {
@@ -64,11 +70,16 @@
 //----------------------------------------------------------------------------
 struct cmTarget::ImportInfo
 {
+  ImportInfo(): NoSOName(false), Multiplicity(0) {}
   bool NoSOName;
+  int Multiplicity;
   std::string Location;
   std::string SOName;
   std::string ImportLibrary;
-  cmTarget::LinkInterface LinkInterface;
+  std::string Languages;
+  std::string Libraries;
+  std::string LibrariesProp;
+  std::string SharedDeps;
 };
 
 //----------------------------------------------------------------------------
@@ -77,11 +88,6 @@
   std::string CompilePdbDir;
 };
 
-struct TargetConfigPair : public std::pair<cmTarget const* , std::string> {
-  TargetConfigPair(cmTarget const* tgt, const std::string &config)
-    : std::pair<cmTarget const* , std::string>(tgt, config) {}
-};
-
 //----------------------------------------------------------------------------
 class cmTargetInternals
 {
@@ -90,11 +96,13 @@
     : Backtrace(NULL)
     {
     this->PolicyWarnedCMP0022 = false;
+    this->UtilityItemsDone = false;
     }
   cmTargetInternals(cmTargetInternals const&)
     : Backtrace(NULL)
     {
     this->PolicyWarnedCMP0022 = false;
+    this->UtilityItemsDone = false;
     }
   ~cmTargetInternals();
 
@@ -105,53 +113,100 @@
   struct OptionalLinkInterface: public cmTarget::LinkInterface
   {
     OptionalLinkInterface():
-      Exists(false), Complete(false), ExplicitLibraries(0) {}
+      LibrariesDone(false), AllDone(false),
+      Exists(false), HadHeadSensitiveCondition(false),
+      ExplicitLibraries(0) {}
+    bool LibrariesDone;
+    bool AllDone;
     bool Exists;
-    bool Complete;
+    bool HadHeadSensitiveCondition;
     const char* ExplicitLibraries;
   };
   void ComputeLinkInterface(cmTarget const* thisTarget,
                             const std::string& config,
                             OptionalLinkInterface& iface,
-                            cmTarget const* head,
-                            const char *explicitLibraries) const;
+                            cmTarget const* head) const;
+  void ComputeLinkInterfaceLibraries(cmTarget const* thisTarget,
+                                     const std::string& config,
+                                     OptionalLinkInterface& iface,
+                                     cmTarget const* head,
+                                     bool usage_requirements_only);
 
-  typedef std::map<TargetConfigPair, OptionalLinkInterface>
+  struct HeadToLinkInterfaceMap:
+    public std::map<cmTarget const*, OptionalLinkInterface> {};
+  typedef std::map<std::string, HeadToLinkInterfaceMap>
                                                           LinkInterfaceMapType;
   LinkInterfaceMapType LinkInterfaceMap;
+  LinkInterfaceMapType LinkInterfaceUsageRequirementsOnlyMap;
   bool PolicyWarnedCMP0022;
 
   typedef std::map<std::string, cmTarget::OutputInfo> OutputInfoMapType;
   OutputInfoMapType OutputInfoMap;
 
-  typedef std::map<TargetConfigPair, cmTarget::ImportInfo>
-                                                            ImportInfoMapType;
+  typedef std::map<std::string, cmTarget::ImportInfo> ImportInfoMapType;
   ImportInfoMapType ImportInfoMap;
 
   typedef std::map<std::string, cmTarget::CompileInfo> CompileInfoMapType;
   CompileInfoMapType CompileInfoMap;
 
   // Cache link implementation computation from each configuration.
-  typedef std::map<TargetConfigPair,
-                   cmTarget::LinkImplementation> LinkImplMapType;
+  struct OptionalLinkImplementation: public cmTarget::LinkImplementation
+  {
+    OptionalLinkImplementation():
+      LibrariesDone(false), LanguagesDone(false),
+      HadHeadSensitiveCondition(false) {}
+    bool LibrariesDone;
+    bool LanguagesDone;
+    bool HadHeadSensitiveCondition;
+  };
+  void ComputeLinkImplementationLibraries(cmTarget const* thisTarget,
+                                          const std::string& config,
+                                          OptionalLinkImplementation& impl,
+                                          cmTarget const* head) const;
+  void ComputeLinkImplementationLanguages(cmTarget const* thisTarget,
+                                          const std::string& config,
+                                          OptionalLinkImplementation& impl
+                                          ) const;
+
+  struct HeadToLinkImplementationMap:
+    public std::map<cmTarget const*, OptionalLinkImplementation> {};
+  typedef std::map<std::string,
+                   HeadToLinkImplementationMap> LinkImplMapType;
   LinkImplMapType LinkImplMap;
 
-  typedef std::map<TargetConfigPair, cmTarget::LinkClosure>
-                                                          LinkClosureMapType;
+  typedef std::map<std::string, cmTarget::LinkClosure> LinkClosureMapType;
   LinkClosureMapType LinkClosureMap;
 
-  typedef std::map<TargetConfigPair, std::vector<cmSourceFile*> >
-                                                          SourceFilesMapType;
+  struct LinkImplClosure: public std::vector<cmTarget const*>
+  {
+    LinkImplClosure(): Done(false) {}
+    bool Done;
+  };
+  std::map<std::string, LinkImplClosure> LinkImplClosureMap;
+
+  struct CompatibleInterfaces: public cmTarget::CompatibleInterfaces
+  {
+    CompatibleInterfaces(): Done(false) {}
+    bool Done;
+  };
+  std::map<std::string, CompatibleInterfaces> CompatibleInterfacesMap;
+
+  typedef std::map<std::string, std::vector<cmSourceFile*> >
+                                                       SourceFilesMapType;
   SourceFilesMapType SourceFilesMap;
 
-  struct TargetPropertyEntry {
+  std::set<cmLinkItem> UtilityItems;
+  bool UtilityItemsDone;
+
+  class TargetPropertyEntry {
+    static cmLinkImplItem NoLinkImplItem;
+  public:
     TargetPropertyEntry(cmsys::auto_ptr<cmCompiledGeneratorExpression> cge,
-      const std::string &targetName = std::string())
-      : ge(cge), TargetName(targetName)
+                        cmLinkImplItem const& item = NoLinkImplItem)
+      : ge(cge), LinkImplItem(item)
     {}
     const cmsys::auto_ptr<cmCompiledGeneratorExpression> ge;
-    std::vector<std::string> CachedEntries;
-    const std::string TargetName;
+    cmLinkImplItem const& LinkImplItem;
   };
   std::vector<TargetPropertyEntry*> IncludeDirectoriesEntries;
   std::vector<TargetPropertyEntry*> CompileOptionsEntries;
@@ -160,26 +215,15 @@
   std::vector<TargetPropertyEntry*> SourceEntries;
   std::vector<cmValueWithOrigin> LinkImplementationPropertyEntries;
 
-  mutable std::map<std::string, std::vector<TargetPropertyEntry*> >
-                                CachedLinkInterfaceIncludeDirectoriesEntries;
-  mutable std::map<std::string, std::vector<TargetPropertyEntry*> >
-                                CachedLinkInterfaceCompileOptionsEntries;
-  mutable std::map<std::string, std::vector<TargetPropertyEntry*> >
-                                CachedLinkInterfaceCompileDefinitionsEntries;
-  mutable std::map<std::string, std::vector<TargetPropertyEntry*> >
-                                CachedLinkInterfaceSourcesEntries;
-  mutable std::map<std::string, std::vector<TargetPropertyEntry*> >
-                                CachedLinkInterfaceCompileFeaturesEntries;
-
-  mutable std::map<std::string, bool> CacheLinkInterfaceIncludeDirectoriesDone;
-  mutable std::map<std::string, bool> CacheLinkInterfaceCompileDefinitionsDone;
-  mutable std::map<std::string, bool> CacheLinkInterfaceCompileOptionsDone;
-  mutable std::map<std::string, bool> CacheLinkInterfaceSourcesDone;
-  mutable std::map<std::string, bool> CacheLinkInterfaceCompileFeaturesDone;
+  void AddInterfaceEntries(
+    cmTarget const* thisTarget, std::string const& config,
+    std::string const& prop, std::vector<TargetPropertyEntry*>& entries);
 };
 
+cmLinkImplItem cmTargetInternals::TargetPropertyEntry::NoLinkImplItem;
+
 //----------------------------------------------------------------------------
-void deleteAndClear(
+static void deleteAndClear(
       std::vector<cmTargetInternals::TargetPropertyEntry*> &entries)
 {
   for (std::vector<cmTargetInternals::TargetPropertyEntry*>::const_iterator
@@ -193,26 +237,8 @@
 }
 
 //----------------------------------------------------------------------------
-void deleteAndClear(
-  std::map<std::string,
-          std::vector<cmTargetInternals::TargetPropertyEntry*> > &entries)
-{
-  for (std::map<std::string,
-          std::vector<cmTargetInternals::TargetPropertyEntry*> >::iterator
-        it = entries.begin(), end = entries.end(); it != end; ++it)
-    {
-    deleteAndClear(it->second);
-    }
-}
-
-//----------------------------------------------------------------------------
 cmTargetInternals::~cmTargetInternals()
 {
-  deleteAndClear(this->CachedLinkInterfaceIncludeDirectoriesEntries);
-  deleteAndClear(this->CachedLinkInterfaceCompileOptionsEntries);
-  deleteAndClear(this->CachedLinkInterfaceCompileFeaturesEntries);
-  deleteAndClear(this->CachedLinkInterfaceCompileDefinitionsEntries);
-  deleteAndClear(this->CachedLinkInterfaceSourcesEntries);
 }
 
 //----------------------------------------------------------------------------
@@ -226,9 +252,12 @@
 #undef INITIALIZE_TARGET_POLICY_MEMBER
 
   this->Makefile = 0;
-  this->LinkLibrariesAnalyzed = false;
+#if defined(_WIN32) && !defined(__CYGWIN__)
+  this->LinkLibrariesForVS6Analyzed = false;
+#endif
   this->HaveInstallRule = false;
   this->DLLPlatform = false;
+  this->IsAndroid = false;
   this->IsApple = false;
   this->IsImportedTarget = false;
   this->BuildInterfaceIncludesAppended = false;
@@ -284,12 +313,18 @@
                        this->Makefile->IsOn("CYGWIN") ||
                        this->Makefile->IsOn("MINGW"));
 
+  // Check whether we are targeting an Android platform.
+  this->IsAndroid =
+    strcmp(this->Makefile->GetSafeDefinition("CMAKE_SYSTEM_NAME"),
+           "Android") == 0;
+
   // Check whether we are targeting an Apple platform.
   this->IsApple = this->Makefile->IsOn("APPLE");
 
   // Setup default property values.
-  if (this->GetType() != INTERFACE_LIBRARY)
+  if (this->GetType() != INTERFACE_LIBRARY && this->GetType() != UTILITY)
     {
+    this->SetPropertyDefault("ANDROID_API", 0);
     this->SetPropertyDefault("INSTALL_NAME_DIR", 0);
     this->SetPropertyDefault("INSTALL_RPATH", "");
     this->SetPropertyDefault("INSTALL_RPATH_USE_LINK_PATH", "OFF");
@@ -329,41 +364,44 @@
   mf->GetConfigurations(configNames);
 
   // Setup per-configuration property default values.
-  const char* configProps[] = {
-    "ARCHIVE_OUTPUT_DIRECTORY_",
-    "LIBRARY_OUTPUT_DIRECTORY_",
-    "RUNTIME_OUTPUT_DIRECTORY_",
-    "PDB_OUTPUT_DIRECTORY_",
-    "COMPILE_PDB_OUTPUT_DIRECTORY_",
-    "MAP_IMPORTED_CONFIG_",
-    0};
-  for(std::vector<std::string>::iterator ci = configNames.begin();
-      ci != configNames.end(); ++ci)
+  if (this->GetType() != UTILITY)
     {
-    std::string configUpper = cmSystemTools::UpperCase(*ci);
-    for(const char** p = configProps; *p; ++p)
+    const char* configProps[] = {
+      "ARCHIVE_OUTPUT_DIRECTORY_",
+      "LIBRARY_OUTPUT_DIRECTORY_",
+      "RUNTIME_OUTPUT_DIRECTORY_",
+      "PDB_OUTPUT_DIRECTORY_",
+      "COMPILE_PDB_OUTPUT_DIRECTORY_",
+      "MAP_IMPORTED_CONFIG_",
+      0};
+    for(std::vector<std::string>::iterator ci = configNames.begin();
+        ci != configNames.end(); ++ci)
       {
-      if (this->TargetTypeValue == INTERFACE_LIBRARY
-          && strcmp(*p, "MAP_IMPORTED_CONFIG_") != 0)
+      std::string configUpper = cmSystemTools::UpperCase(*ci);
+      for(const char** p = configProps; *p; ++p)
         {
-        continue;
+        if (this->TargetTypeValue == INTERFACE_LIBRARY
+            && strcmp(*p, "MAP_IMPORTED_CONFIG_") != 0)
+          {
+          continue;
+          }
+        std::string property = *p;
+        property += configUpper;
+        this->SetPropertyDefault(property, 0);
         }
-      std::string property = *p;
-      property += configUpper;
-      this->SetPropertyDefault(property, 0);
-      }
 
-    // Initialize per-configuration name postfix property from the
-    // variable only for non-executable targets.  This preserves
-    // compatibility with previous CMake versions in which executables
-    // did not support this variable.  Projects may still specify the
-    // property directly.
-    if(this->TargetTypeValue != cmTarget::EXECUTABLE
-        && this->TargetTypeValue != cmTarget::INTERFACE_LIBRARY)
-      {
-      std::string property = cmSystemTools::UpperCase(*ci);
-      property += "_POSTFIX";
-      this->SetPropertyDefault(property, 0);
+      // Initialize per-configuration name postfix property from the
+      // variable only for non-executable targets.  This preserves
+      // compatibility with previous CMake versions in which executables
+      // did not support this variable.  Projects may still specify the
+      // property directly.
+      if(this->TargetTypeValue != cmTarget::EXECUTABLE
+          && this->TargetTypeValue != cmTarget::INTERFACE_LIBRARY)
+        {
+        std::string property = cmSystemTools::UpperCase(*ci);
+        property += "_POSTFIX";
+        this->SetPropertyDefault(property, 0);
+        }
       }
     }
 
@@ -402,19 +440,23 @@
       }
     }
 
-  if (this->GetType() != INTERFACE_LIBRARY)
+  if (this->GetType() != INTERFACE_LIBRARY && this->GetType() != UTILITY)
     {
     this->SetPropertyDefault("C_VISIBILITY_PRESET", 0);
     this->SetPropertyDefault("CXX_VISIBILITY_PRESET", 0);
     this->SetPropertyDefault("VISIBILITY_INLINES_HIDDEN", 0);
     }
 
+  if(this->TargetTypeValue == cmTarget::EXECUTABLE)
+    {
+    this->SetPropertyDefault("ANDROID_GUI", 0);
+    }
   if(this->TargetTypeValue == cmTarget::SHARED_LIBRARY
       || this->TargetTypeValue == cmTarget::MODULE_LIBRARY)
     {
     this->SetProperty("POSITION_INDEPENDENT_CODE", "True");
     }
-  if (this->GetType() != INTERFACE_LIBRARY)
+  if (this->GetType() != INTERFACE_LIBRARY && this->GetType() != UTILITY)
     {
     this->SetPropertyDefault("POSITION_INDEPENDENT_CODE", 0);
     }
@@ -436,8 +478,11 @@
     this->PolicyStatusCMP0022 = cmPolicies::NEW;
     }
 
-  this->SetPropertyDefault("JOB_POOL_COMPILE", 0);
-  this->SetPropertyDefault("JOB_POOL_LINK", 0);
+  if (this->GetType() != INTERFACE_LIBRARY && this->GetType() != UTILITY)
+    {
+    this->SetPropertyDefault("JOB_POOL_COMPILE", 0);
+    this->SetPropertyDefault("JOB_POOL_LINK", 0);
+    }
 }
 
 //----------------------------------------------------------------------------
@@ -461,6 +506,22 @@
 }
 
 //----------------------------------------------------------------------------
+std::set<cmLinkItem> const& cmTarget::GetUtilityItems() const
+{
+  if(!this->Internal->UtilityItemsDone)
+    {
+    this->Internal->UtilityItemsDone = true;
+    for(std::set<std::string>::const_iterator i = this->Utilities.begin();
+        i != this->Utilities.end(); ++i)
+      {
+      this->Internal->UtilityItems.insert(
+        cmLinkItem(*i, this->Makefile->FindTargetToUse(*i)));
+      }
+    }
+  return this->Internal->UtilityItems;
+}
+
+//----------------------------------------------------------------------------
 void cmTarget::FinishConfigure()
 {
   // Erase any cached link information that might have been comptued
@@ -469,8 +530,13 @@
   // invalidation code in this source file is buggy.
   this->ClearLinkMaps();
 
-  // Do old-style link dependency analysis.
-  this->AnalyzeLibDependencies(*this->Makefile);
+#if defined(_WIN32) && !defined(__CYGWIN__)
+  // Do old-style link dependency analysis only for CM_USE_OLD_VS6.
+  if(this->Makefile->GetLocalGenerator()->GetGlobalGenerator()->IsForVS6())
+    {
+    this->AnalyzeLibDependenciesForVS6(*this->Makefile);
+    }
+#endif
 }
 
 //----------------------------------------------------------------------------
@@ -479,6 +545,7 @@
   this->LinkImplementationLanguageIsContextDependent = true;
   this->Internal->LinkImplMap.clear();
   this->Internal->LinkInterfaceMap.clear();
+  this->Internal->LinkInterfaceUsageRequirementsOnlyMap.clear();
   this->Internal->LinkClosureMap.clear();
   for (cmTargetLinkInformationMap::const_iterator it
       = this->LinkInformation.begin();
@@ -571,9 +638,8 @@
 static bool processSources(cmTarget const* tgt,
       const std::vector<cmTargetInternals::TargetPropertyEntry*> &entries,
       std::vector<std::string> &srcs,
-      std::set<std::string> &uniqueSrcs,
+      UNORDERED_SET<std::string> &uniqueSrcs,
       cmGeneratorExpressionDAGChecker *dagChecker,
-      cmTarget const* head,
       std::string const& config, bool debugSources)
 {
   cmMakefile *mf = tgt->GetMakefile();
@@ -583,49 +649,37 @@
   for (std::vector<cmTargetInternals::TargetPropertyEntry*>::const_iterator
       it = entries.begin(), end = entries.end(); it != end; ++it)
     {
-    bool cacheSources = false;
-    std::vector<std::string> entrySources = (*it)->CachedEntries;
-    if(entrySources.empty())
+    std::vector<std::string> entrySources;
+    cmSystemTools::ExpandListArgument((*it)->ge->Evaluate(mf,
+                                              config,
+                                              false,
+                                              tgt,
+                                              tgt,
+                                              dagChecker),
+                                    entrySources);
+
+    if ((*it)->ge->GetHadContextSensitiveCondition())
       {
-      cmSystemTools::ExpandListArgument((*it)->ge->Evaluate(mf,
-                                                config,
-                                                false,
-                                                head ? head : tgt,
-                                                tgt,
-                                                dagChecker),
-                                      entrySources);
+      contextDependent = true;
+      }
 
-      if ((*it)->ge->GetHadContextSensitiveCondition())
-        {
-        contextDependent = true;
-        }
-      else if (mf->IsGeneratingBuildSystem())
-        {
-        cacheSources = true;
-        }
+    for(std::vector<std::string>::iterator i = entrySources.begin();
+        i != entrySources.end(); ++i)
+      {
+      std::string& src = *i;
 
-      for(std::vector<std::string>::iterator i = entrySources.begin();
-          i != entrySources.end(); ++i)
+      cmSourceFile* sf = mf->GetOrCreateSource(src);
+      std::string e;
+      src = sf->GetFullPath(&e);
+      if(src.empty())
         {
-        std::string& src = *i;
-
-        cmSourceFile* sf = mf->GetOrCreateSource(src);
-        std::string e;
-        src = sf->GetFullPath(&e);
-        if(src.empty())
+        if(!e.empty())
           {
-          if(!e.empty())
-            {
-            cmake* cm = mf->GetCMakeInstance();
-            cm->IssueMessage(cmake::FATAL_ERROR, e,
-                            tgt->GetBacktrace());
-            }
-          return contextDependent;
+          cmake* cm = mf->GetCMakeInstance();
+          cm->IssueMessage(cmake::FATAL_ERROR, e,
+                          tgt->GetBacktrace());
           }
-        }
-      if (cacheSources)
-        {
-        (*it)->CachedEntries = entrySources;
+        return contextDependent;
         }
       }
     std::string usedSources;
@@ -656,8 +710,7 @@
 
 //----------------------------------------------------------------------------
 void cmTarget::GetSourceFiles(std::vector<std::string> &files,
-                              const std::string& config,
-                              cmTarget const* head) const
+                              const std::string& config) const
 {
   assert(this->GetType() != INTERFACE_LIBRARY);
 
@@ -715,66 +768,28 @@
   cmGeneratorExpressionDAGChecker dagChecker(this->GetName(),
                                              "SOURCES", 0, 0);
 
-  std::set<std::string> uniqueSrcs;
+  UNORDERED_SET<std::string> uniqueSrcs;
   bool contextDependentDirectSources = processSources(this,
                  this->Internal->SourceEntries,
                  files,
                  uniqueSrcs,
                  &dagChecker,
-                 head,
                  config,
                  debugSources);
 
-  if (!this->Internal->CacheLinkInterfaceSourcesDone[config])
-    {
-    for (std::vector<cmValueWithOrigin>::const_iterator
-        it = this->Internal->LinkImplementationPropertyEntries.begin(),
-        end = this->Internal->LinkImplementationPropertyEntries.end();
-        it != end; ++it)
-      {
-      if (!cmGeneratorExpression::IsValidTargetName(it->Value)
-          && cmGeneratorExpression::Find(it->Value) == std::string::npos)
-        {
-        continue;
-        }
-      {
-      cmGeneratorExpression ge;
-      cmsys::auto_ptr<cmCompiledGeneratorExpression> cge =
-                                                        ge.Parse(it->Value);
-      std::string targetResult = cge->Evaluate(this->Makefile, config,
-                                        false, this, 0, &dagChecker);
-      if (!this->Makefile->FindTargetToUse(targetResult))
-        {
-        continue;
-        }
-      }
-      std::string sourceGenex = "$<TARGET_PROPERTY:" +
-                              it->Value + ",INTERFACE_SOURCES>";
-      if (cmGeneratorExpression::Find(it->Value) != std::string::npos)
-        {
-        // Because it->Value is a generator expression, ensure that it
-        // evaluates to the non-empty string before being used in the
-        // TARGET_PROPERTY expression.
-        sourceGenex = "$<$<BOOL:" + it->Value + ">:" + sourceGenex + ">";
-        }
-      cmGeneratorExpression ge(&it->Backtrace);
-      cmsys::auto_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(
-                                                                sourceGenex);
+  std::vector<cmTargetInternals::TargetPropertyEntry*>
+    linkInterfaceSourcesEntries;
 
-      this->Internal
-        ->CachedLinkInterfaceSourcesEntries[config].push_back(
-                        new cmTargetInternals::TargetPropertyEntry(cge,
-                                                              it->Value));
-      }
-    }
+  this->Internal->AddInterfaceEntries(
+    this, config, "INTERFACE_SOURCES",
+    linkInterfaceSourcesEntries);
 
-    std::vector<std::string>::size_type numFilesBefore = files.size();
-    bool contextDependentInterfaceSources = processSources(this,
-    this->Internal->CachedLinkInterfaceSourcesEntries[config],
+  std::vector<std::string>::size_type numFilesBefore = files.size();
+  bool contextDependentInterfaceSources = processSources(this,
+    linkInterfaceSourcesEntries,
                             files,
                             uniqueSrcs,
                             &dagChecker,
-                            head,
                             config,
                             debugSources);
 
@@ -784,14 +799,7 @@
     this->LinkImplementationLanguageIsContextDependent = false;
     }
 
-  if (!this->Makefile->IsGeneratingBuildSystem())
-    {
-    deleteAndClear(this->Internal->CachedLinkInterfaceSourcesEntries);
-    }
-  else
-    {
-    this->Internal->CacheLinkInterfaceSourcesDone[config] = true;
-    }
+  deleteAndClear(linkInterfaceSourcesEntries);
 }
 
 //----------------------------------------------------------------------------
@@ -853,12 +861,11 @@
 
 //----------------------------------------------------------------------------
 void cmTarget::GetSourceFiles(std::vector<cmSourceFile*> &files,
-                              const std::string& config,
-                              cmTarget const* head) const
+                              const std::string& config) const
 {
 
   // Lookup any existing link implementation for this configuration.
-  TargetConfigPair key(head, cmSystemTools::UpperCase(config));
+  std::string key = cmSystemTools::UpperCase(config);
 
   if(!this->LinkImplementationLanguageIsContextDependent)
     {
@@ -875,7 +882,7 @@
   else
     {
     std::vector<std::string> srcs;
-    this->GetSourceFiles(srcs, config, head);
+    this->GetSourceFiles(srcs, config);
 
     std::set<cmSourceFile*> emitted;
 
@@ -931,10 +938,13 @@
 
     if(!(src[0] == '$' && src[1] == '<'))
       {
-      filename = this->ProcessSourceItemCMP0049(filename);
-      if (cmSystemTools::GetErrorOccuredFlag())
+      if(!filename.empty())
         {
-        return;
+        filename = this->ProcessSourceItemCMP0049(filename);
+        if(filename.empty())
+          {
+          return;
+          }
         }
       this->Makefile->GetOrCreateSource(filename);
       }
@@ -1002,8 +1012,7 @@
 cmSourceFile* cmTarget::AddSourceCMP0049(const std::string& s)
 {
   std::string src = this->ProcessSourceItemCMP0049(s);
-
-  if (cmSystemTools::GetErrorOccuredFlag())
+  if(!s.empty() && src.empty())
     {
     return 0;
     }
@@ -1195,63 +1204,6 @@
 }
 
 //----------------------------------------------------------------------------
-void cmTarget::GetDirectLinkLibraries(const std::string& config,
-                            std::vector<std::string> &libs,
-                            cmTarget const* head) const
-{
-  const char *prop = this->GetProperty("LINK_LIBRARIES");
-  if (prop)
-    {
-    cmGeneratorExpression ge;
-    const cmsys::auto_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(prop);
-
-    cmGeneratorExpressionDAGChecker dagChecker(
-                                        this->GetName(),
-                                        "LINK_LIBRARIES", 0, 0);
-    cmSystemTools::ExpandListArgument(cge->Evaluate(this->Makefile,
-                                        config,
-                                        false,
-                                        head,
-                                        &dagChecker),
-                                      libs);
-
-    std::set<std::string> const& seenProps = cge->GetSeenTargetProperties();
-    for (std::set<std::string>::const_iterator it = seenProps.begin();
-        it != seenProps.end(); ++it)
-      {
-      if (!this->GetProperty(*it))
-        {
-        this->LinkImplicitNullProperties.insert(*it);
-        }
-      }
-    cge->GetMaxLanguageStandard(this, this->MaxLanguageStandards);
-    }
-}
-
-//----------------------------------------------------------------------------
-void cmTarget::GetInterfaceLinkLibraries(const std::string& config,
-                                         std::vector<std::string> &libs,
-                                         cmTarget const* head) const
-{
-  const char *prop = this->GetProperty("INTERFACE_LINK_LIBRARIES");
-  if (prop)
-    {
-    cmGeneratorExpression ge;
-    const cmsys::auto_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(prop);
-
-    cmGeneratorExpressionDAGChecker dagChecker(
-                                        this->GetName(),
-                                        "INTERFACE_LINK_LIBRARIES", 0, 0);
-    cmSystemTools::ExpandListArgument(cge->Evaluate(this->Makefile,
-                                        config,
-                                        false,
-                                        head,
-                                        &dagChecker),
-                                      libs);
-    }
-}
-
-//----------------------------------------------------------------------------
 std::string cmTarget::GetDebugGeneratorExpressions(const std::string &value,
                                   cmTarget::LinkLibraryType llt) const
 {
@@ -1325,7 +1277,7 @@
                         = (sig == cmTarget::KeywordTLLSignature ? "keyword"
                                                                 : "plain");
     s << "The uses of the " << sigString << " signature are here:\n";
-    std::set<std::string> emitted;
+    UNORDERED_SET<std::string> emitted;
     for(std::vector<cmListFileBacktrace>::iterator it = sigs.begin();
         it != sigs.end(); ++it)
       {
@@ -1374,7 +1326,9 @@
   cmTarget::LibraryID tmp;
   tmp.first = lib;
   tmp.second = llt;
-  this->LinkLibraries.push_back( tmp );
+#if defined(_WIN32) && !defined(__CYGWIN__)
+  this->LinkLibrariesForVS6.push_back( tmp );
+#endif
   this->OriginalLinkLibraries.push_back(tmp);
   this->ClearLinkMaps();
 
@@ -1440,9 +1394,10 @@
     }
 }
 
+#if defined(_WIN32) && !defined(__CYGWIN__)
 //----------------------------------------------------------------------------
 void
-cmTarget::AnalyzeLibDependencies( const cmMakefile& mf )
+cmTarget::AnalyzeLibDependenciesForVS6( const cmMakefile& mf )
 {
   // There are two key parts of the dependency analysis: (1)
   // determining the libraries in the link line, and (2) constructing
@@ -1519,8 +1474,8 @@
  // eventually be removed.  This code was moved here from the end of
  // old source list processing code which was called just before this
  // method.
- for(LinkLibraryVectorType::iterator p = this->LinkLibraries.begin();
-     p != this->LinkLibraries.end(); ++p)
+ for(LinkLibraryVectorType::iterator p = this->LinkLibrariesForVS6.begin();
+     p != this->LinkLibrariesForVS6.end(); ++p)
    {
    this->Makefile->ExpandVariablesInString(p->first, true, true);
    }
@@ -1532,22 +1487,22 @@
  // 1. Build the dependency graph
  //
  for(LinkLibraryVectorType::reverse_iterator lib
-       = this->LinkLibraries.rbegin();
-     lib != this->LinkLibraries.rend(); ++lib)
+       = this->LinkLibrariesForVS6.rbegin();
+     lib != this->LinkLibrariesForVS6.rend(); ++lib)
    {
-   this->GatherDependencies( mf, *lib, dep_map);
+   this->GatherDependenciesForVS6( mf, *lib, dep_map);
    }
 
  // 2. Remove any dependencies that are already satisfied in the original
  // link line.
  //
- for(LinkLibraryVectorType::iterator lib = this->LinkLibraries.begin();
-     lib != this->LinkLibraries.end(); ++lib)
+ for(LinkLibraryVectorType::iterator lib = this->LinkLibrariesForVS6.begin();
+     lib != this->LinkLibrariesForVS6.end(); ++lib)
    {
    for( LinkLibraryVectorType::iterator lib2 = lib;
-        lib2 != this->LinkLibraries.end(); ++lib2)
+        lib2 != this->LinkLibrariesForVS6.end(); ++lib2)
      {
-     this->DeleteDependency( dep_map, *lib, *lib2);
+     this->DeleteDependencyForVS6( dep_map, *lib, *lib2);
      }
    }
 
@@ -1556,43 +1511,43 @@
  // missing.  Start from the back and keep adding.
  //
  std::set<DependencyMap::key_type> done, visited;
- std::vector<DependencyMap::key_type> newLinkLibraries;
+ std::vector<DependencyMap::key_type> newLinkLibrariesForVS6;
  for(LinkLibraryVectorType::reverse_iterator lib =
-       this->LinkLibraries.rbegin();
-     lib != this->LinkLibraries.rend(); ++lib)
+       this->LinkLibrariesForVS6.rbegin();
+     lib != this->LinkLibrariesForVS6.rend(); ++lib)
    {
    // skip zero size library entries, this may happen
    // if a variable expands to nothing.
    if (lib->first.size() != 0)
      {
-     this->Emit( *lib, dep_map, done, visited, newLinkLibraries );
+     this->EmitForVS6( *lib, dep_map, done, visited, newLinkLibrariesForVS6 );
      }
    }
 
  // 4. Add the new libraries to the link line.
  //
  for( std::vector<DependencyMap::key_type>::reverse_iterator k =
-        newLinkLibraries.rbegin();
-      k != newLinkLibraries.rend(); ++k )
+        newLinkLibrariesForVS6.rbegin();
+      k != newLinkLibrariesForVS6.rend(); ++k )
    {
    // get the llt from the dep_map
-   this->LinkLibraries.push_back( std::make_pair(k->first,k->second) );
+   this->LinkLibrariesForVS6.push_back( std::make_pair(k->first,k->second) );
    }
- this->LinkLibrariesAnalyzed = true;
+ this->LinkLibrariesForVS6Analyzed = true;
 }
 
 //----------------------------------------------------------------------------
-void cmTarget::InsertDependency( DependencyMap& depMap,
-                                 const LibraryID& lib,
-                                 const LibraryID& dep)
+void cmTarget::InsertDependencyForVS6( DependencyMap& depMap,
+                                       const LibraryID& lib,
+                                       const LibraryID& dep)
 {
   depMap[lib].push_back(dep);
 }
 
 //----------------------------------------------------------------------------
-void cmTarget::DeleteDependency( DependencyMap& depMap,
-                                 const LibraryID& lib,
-                                 const LibraryID& dep)
+void cmTarget::DeleteDependencyForVS6( DependencyMap& depMap,
+                                       const LibraryID& lib,
+                                       const LibraryID& dep)
 {
   // Make sure there is an entry in the map for lib. If so, delete all
   // dependencies to dep. There may be repeated entries because of
@@ -1611,11 +1566,11 @@
 }
 
 //----------------------------------------------------------------------------
-void cmTarget::Emit(const LibraryID lib,
-                    const DependencyMap& dep_map,
-                    std::set<LibraryID>& emitted,
-                    std::set<LibraryID>& visited,
-                    DependencyList& link_line )
+void cmTarget::EmitForVS6(const LibraryID lib,
+                          const DependencyMap& dep_map,
+                          std::set<LibraryID>& emitted,
+                          std::set<LibraryID>& visited,
+                          DependencyList& link_line )
 {
   // It's already been emitted
   if( emitted.find(lib) != emitted.end() )
@@ -1661,7 +1616,7 @@
           if( emitted.find(*i) == emitted.end() )
             {
             // emit dependencies
-            Emit( *i, dep_map, emitted, visited, link_line );
+            this->EmitForVS6( *i, dep_map, emitted, visited, link_line );
             // emit self
             emitted.insert(*i);
             emitted_here.insert(*i);
@@ -1674,9 +1629,9 @@
 }
 
 //----------------------------------------------------------------------------
-void cmTarget::GatherDependencies( const cmMakefile& mf,
-                                   const LibraryID& lib,
-                                   DependencyMap& dep_map)
+void cmTarget::GatherDependenciesForVS6( const cmMakefile& mf,
+                                         const LibraryID& lib,
+                                         DependencyMap& dep_map)
 {
   // If the library is already in the dependency map, then it has
   // already been fully processed.
@@ -1720,8 +1675,8 @@
         else
           {
           LibraryID lib2(l,llt);
-          this->InsertDependency( dep_map, lib, lib2);
-          this->GatherDependencies( mf, lib2, dep_map);
+          this->InsertDependencyForVS6( dep_map, lib, lib2);
+          this->GatherDependenciesForVS6( mf, lib2, dep_map);
           llt = cmTarget::GENERAL;
           }
         }
@@ -1729,9 +1684,10 @@
       end = depline.find( ";", start );
       }
     // cannot depend on itself
-    this->DeleteDependency( dep_map, lib, lib);
+    this->DeleteDependencyForVS6( dep_map, lib, lib);
     }
 }
+#endif
 
 //----------------------------------------------------------------------------
 static bool whiteListedInterfaceProperty(const std::string& prop)
@@ -1740,22 +1696,20 @@
     {
     return true;
     }
-  static const char* builtIns[] = {
-    // ###: This must remain sorted. It is processed with a binary search.
-    "COMPATIBLE_INTERFACE_BOOL",
-    "COMPATIBLE_INTERFACE_NUMBER_MAX",
-    "COMPATIBLE_INTERFACE_NUMBER_MIN",
-    "COMPATIBLE_INTERFACE_STRING",
-    "EXPORT_NAME",
-    "IMPORTED",
-    "NAME",
-    "TYPE"
-  };
+  static UNORDERED_SET<std::string> builtIns;
+  if (builtIns.empty())
+    {
+    builtIns.insert("COMPATIBLE_INTERFACE_BOOL");
+    builtIns.insert("COMPATIBLE_INTERFACE_NUMBER_MAX");
+    builtIns.insert("COMPATIBLE_INTERFACE_NUMBER_MIN");
+    builtIns.insert("COMPATIBLE_INTERFACE_STRING");
+    builtIns.insert("EXPORT_NAME");
+    builtIns.insert("IMPORTED");
+    builtIns.insert("NAME");
+    builtIns.insert("TYPE");
+    }
 
-  if (std::binary_search(cmArrayBegin(builtIns),
-                         cmArrayEnd(builtIns),
-                         prop.c_str(),
-                         cmStrCmp(prop)))
+  if (builtIns.count(prop))
     {
     return true;
     }
@@ -1780,15 +1734,14 @@
     this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
     return;
     }
-
-  if (prop == "NAME")
+  else if (prop == "NAME")
     {
     cmOStringStream e;
     e << "NAME property is read-only\n";
     this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
     return;
     }
-  if(prop == "INCLUDE_DIRECTORIES")
+  else if(prop == "INCLUDE_DIRECTORIES")
     {
     cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
     cmGeneratorExpression ge(&lfbt);
@@ -1796,9 +1749,8 @@
     cmsys::auto_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(value);
     this->Internal->IncludeDirectoriesEntries.push_back(
                           new cmTargetInternals::TargetPropertyEntry(cge));
-    return;
     }
-  if(prop == "COMPILE_OPTIONS")
+  else if(prop == "COMPILE_OPTIONS")
     {
     cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
     cmGeneratorExpression ge(&lfbt);
@@ -1806,9 +1758,8 @@
     cmsys::auto_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(value);
     this->Internal->CompileOptionsEntries.push_back(
                           new cmTargetInternals::TargetPropertyEntry(cge));
-    return;
     }
-  if(prop == "COMPILE_FEATURES")
+  else if(prop == "COMPILE_FEATURES")
     {
     cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
     cmGeneratorExpression ge(&lfbt);
@@ -1816,9 +1767,8 @@
     cmsys::auto_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(value);
     this->Internal->CompileFeaturesEntries.push_back(
                           new cmTargetInternals::TargetPropertyEntry(cge));
-    return;
     }
-  if(prop == "COMPILE_DEFINITIONS")
+  else if(prop == "COMPILE_DEFINITIONS")
     {
     cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
     cmGeneratorExpression ge(&lfbt);
@@ -1826,25 +1776,22 @@
     cmsys::auto_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(value);
     this->Internal->CompileDefinitionsEntries.push_back(
                           new cmTargetInternals::TargetPropertyEntry(cge));
-    return;
     }
-  if(prop == "EXPORT_NAME" && this->IsImported())
+  else if(prop == "EXPORT_NAME" && this->IsImported())
     {
     cmOStringStream e;
     e << "EXPORT_NAME property can't be set on imported targets (\""
           << this->Name << "\")\n";
     this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
-    return;
     }
-  if (prop == "LINK_LIBRARIES")
+  else if (prop == "LINK_LIBRARIES")
     {
     this->Internal->LinkImplementationPropertyEntries.clear();
     cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
     cmValueWithOrigin entry(value, lfbt);
     this->Internal->LinkImplementationPropertyEntries.push_back(entry);
-    return;
     }
-  if (prop == "SOURCES")
+  else if (prop == "SOURCES")
     {
     if(this->IsImported())
       {
@@ -1861,10 +1808,12 @@
     cmsys::auto_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(value);
     this->Internal->SourceEntries.push_back(
                           new cmTargetInternals::TargetPropertyEntry(cge));
-    return;
     }
-  this->Properties.SetProperty(prop, value, cmProperty::TARGET);
-  this->MaybeInvalidatePropertyCache(prop);
+  else
+    {
+    this->Properties.SetProperty(prop, value, cmProperty::TARGET);
+    this->MaybeInvalidatePropertyCache(prop);
+    }
 }
 
 //----------------------------------------------------------------------------
@@ -1880,61 +1829,55 @@
     this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
     return;
     }
-  if (prop == "NAME")
+  else if (prop == "NAME")
     {
     cmOStringStream e;
     e << "NAME property is read-only\n";
     this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
     return;
     }
-  if(prop == "INCLUDE_DIRECTORIES")
+  else if(prop == "INCLUDE_DIRECTORIES")
     {
     cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
     cmGeneratorExpression ge(&lfbt);
     this->Internal->IncludeDirectoriesEntries.push_back(
               new cmTargetInternals::TargetPropertyEntry(ge.Parse(value)));
-    return;
     }
-  if(prop == "COMPILE_OPTIONS")
+  else if(prop == "COMPILE_OPTIONS")
     {
     cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
     cmGeneratorExpression ge(&lfbt);
     this->Internal->CompileOptionsEntries.push_back(
               new cmTargetInternals::TargetPropertyEntry(ge.Parse(value)));
-    return;
     }
-  if(prop == "COMPILE_FEATURES")
+  else if(prop == "COMPILE_FEATURES")
     {
     cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
     cmGeneratorExpression ge(&lfbt);
     this->Internal->CompileFeaturesEntries.push_back(
               new cmTargetInternals::TargetPropertyEntry(ge.Parse(value)));
-    return;
     }
-  if(prop == "COMPILE_DEFINITIONS")
+  else if(prop == "COMPILE_DEFINITIONS")
     {
     cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
     cmGeneratorExpression ge(&lfbt);
     this->Internal->CompileDefinitionsEntries.push_back(
               new cmTargetInternals::TargetPropertyEntry(ge.Parse(value)));
-    return;
     }
-  if(prop == "EXPORT_NAME" && this->IsImported())
+  else if(prop == "EXPORT_NAME" && this->IsImported())
     {
     cmOStringStream e;
     e << "EXPORT_NAME property can't be set on imported targets (\""
           << this->Name << "\")\n";
     this->Makefile->IssueMessage(cmake::FATAL_ERROR, e.str());
-    return;
     }
-  if (prop == "LINK_LIBRARIES")
+  else if (prop == "LINK_LIBRARIES")
     {
     cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
     cmValueWithOrigin entry(value, lfbt);
     this->Internal->LinkImplementationPropertyEntries.push_back(entry);
-    return;
     }
-  if (prop == "SOURCES")
+  else if (prop == "SOURCES")
     {
     if(this->IsImported())
       {
@@ -1950,10 +1893,12 @@
       cmsys::auto_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(value);
       this->Internal->SourceEntries.push_back(
                             new cmTargetInternals::TargetPropertyEntry(cge));
-    return;
     }
-  this->Properties.AppendProperty(prop, value, cmProperty::TARGET, asString);
-  this->MaybeInvalidatePropertyCache(prop);
+  else
+    {
+    this->Properties.AppendProperty(prop, value, cmProperty::TARGET, asString);
+    this->MaybeInvalidatePropertyCache(prop);
+    }
 }
 
 //----------------------------------------------------------------------------
@@ -2049,7 +1994,7 @@
 static void processIncludeDirectories(cmTarget const* tgt,
       const std::vector<cmTargetInternals::TargetPropertyEntry*> &entries,
       std::vector<std::string> &includes,
-      std::set<std::string> &uniqueIncludes,
+      UNORDERED_SET<std::string> &uniqueIncludes,
       cmGeneratorExpressionDAGChecker *dagChecker,
       const std::string& config, bool debugIncludes)
 {
@@ -2058,61 +2003,28 @@
   for (std::vector<cmTargetInternals::TargetPropertyEntry*>::const_iterator
       it = entries.begin(), end = entries.end(); it != end; ++it)
     {
-    bool testIsOff = true;
-    bool cacheIncludes = false;
-    std::vector<std::string>& entryIncludes = (*it)->CachedEntries;
-    if(!entryIncludes.empty())
-      {
-      testIsOff = false;
-      }
-    else
-      {
-      cmSystemTools::ExpandListArgument((*it)->ge->Evaluate(mf,
-                                                config,
-                                                false,
-                                                tgt,
-                                                dagChecker),
-                                      entryIncludes);
-      if (mf->IsGeneratingBuildSystem()
-          && !(*it)->ge->GetHadContextSensitiveCondition())
-        {
-        cacheIncludes = true;
-        }
-      }
+    cmLinkImplItem const& item = (*it)->LinkImplItem;
+    std::string const& targetName = item;
+    bool const fromImported = item.Target && item.Target->IsImported();
+    bool const checkCMP0027 = item.FromGenex;
+    std::vector<std::string> entryIncludes;
+    cmSystemTools::ExpandListArgument((*it)->ge->Evaluate(mf,
+                                              config,
+                                              false,
+                                              tgt,
+                                              dagChecker),
+                                    entryIncludes);
+
     std::string usedIncludes;
     for(std::vector<std::string>::iterator
           li = entryIncludes.begin(); li != entryIncludes.end(); ++li)
       {
-      std::string targetName = (*it)->TargetName;
-      std::string evaluatedTargetName;
-      {
-      cmGeneratorExpression ge;
-      cmsys::auto_ptr<cmCompiledGeneratorExpression> cge =
-                                                        ge.Parse(targetName);
-      evaluatedTargetName = cge->Evaluate(mf, config, false, tgt, 0, 0);
-      }
-
-      cmTarget *dependentTarget = mf->FindTargetToUse(targetName);
-
-      const bool fromImported = dependentTarget
-                             && dependentTarget->IsImported();
-
-      cmTarget *evaluatedDependentTarget =
-        (targetName != evaluatedTargetName)
-          ? mf->FindTargetToUse(evaluatedTargetName)
-          : 0;
-
-      targetName = evaluatedTargetName;
-
-      const bool fromEvaluatedImported = evaluatedDependentTarget
-                             && evaluatedDependentTarget->IsImported();
-
-      if ((fromImported || fromEvaluatedImported)
+      if (fromImported
           && !cmSystemTools::FileExists(li->c_str()))
         {
         cmOStringStream e;
         cmake::MessageType messageType = cmake::FATAL_ERROR;
-        if (fromEvaluatedImported)
+        if (checkCMP0027)
           {
           switch(tgt->GetPolicyStatusCMP0027())
             {
@@ -2184,7 +2096,7 @@
           }
         }
 
-      if (testIsOff && !cmSystemTools::IsOff(li->c_str()))
+      if (!cmSystemTools::IsOff(li->c_str()))
         {
         cmSystemTools::ConvertToUnixSlashes(*li);
         }
@@ -2199,10 +2111,6 @@
           }
         }
       }
-    if (cacheIncludes)
-      {
-      (*it)->CachedEntries = entryIncludes;
-      }
     if (!usedIncludes.empty())
       {
       mf->GetCMakeInstance()->IssueMessage(cmake::LOG,
@@ -2218,7 +2126,7 @@
 cmTarget::GetIncludeDirectories(const std::string& config) const
 {
   std::vector<std::string> includes;
-  std::set<std::string> uniqueIncludes;
+  UNORDERED_SET<std::string> uniqueIncludes;
 
   cmGeneratorExpressionDAGChecker dagChecker(this->GetName(),
                                              "INCLUDE_DIRECTORIES", 0, 0);
@@ -2250,95 +2158,47 @@
                             config,
                             debugIncludes);
 
-  if (!this->Internal->CacheLinkInterfaceIncludeDirectoriesDone[config])
+  std::vector<cmTargetInternals::TargetPropertyEntry*>
+    linkInterfaceIncludeDirectoriesEntries;
+  this->Internal->AddInterfaceEntries(
+    this, config, "INTERFACE_INCLUDE_DIRECTORIES",
+    linkInterfaceIncludeDirectoriesEntries);
+
+  if(this->Makefile->IsOn("APPLE"))
     {
-    for (std::vector<cmValueWithOrigin>::const_iterator
-        it = this->Internal->LinkImplementationPropertyEntries.begin(),
-        end = this->Internal->LinkImplementationPropertyEntries.end();
-        it != end; ++it)
+    LinkImplementation const* impl = this->GetLinkImplementation(config);
+    for(std::vector<cmLinkImplItem>::const_iterator
+        it = impl->Libraries.begin();
+        it != impl->Libraries.end(); ++it)
       {
-      if (!cmGeneratorExpression::IsValidTargetName(it->Value)
-          && cmGeneratorExpression::Find(it->Value) == std::string::npos)
+      std::string libDir = cmSystemTools::CollapseFullPath(it->c_str());
+
+      static cmsys::RegularExpression
+        frameworkCheck("(.*\\.framework)(/Versions/[^/]+)?/[^/]+$");
+      if(!frameworkCheck.find(libDir))
         {
         continue;
         }
-      {
+
+      libDir = frameworkCheck.match(1);
+
       cmGeneratorExpression ge;
       cmsys::auto_ptr<cmCompiledGeneratorExpression> cge =
-                                                        ge.Parse(it->Value);
-      std::string result = cge->Evaluate(this->Makefile, config,
-                                        false, this, 0, 0);
-      if (!this->Makefile->FindTargetToUse(result))
-        {
-        continue;
-        }
-      }
-      std::string includeGenex = "$<TARGET_PROPERTY:" +
-                              it->Value + ",INTERFACE_INCLUDE_DIRECTORIES>";
-      if (cmGeneratorExpression::Find(it->Value) != std::string::npos)
-        {
-        // Because it->Value is a generator expression, ensure that it
-        // evaluates to the non-empty string before being used in the
-        // TARGET_PROPERTY expression.
-        includeGenex = "$<$<BOOL:" + it->Value + ">:" + includeGenex + ">";
-        }
-      cmGeneratorExpression ge(&it->Backtrace);
-      cmsys::auto_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(
-                                                              includeGenex);
-
-      this->Internal
-        ->CachedLinkInterfaceIncludeDirectoriesEntries[config].push_back(
-                        new cmTargetInternals::TargetPropertyEntry(cge,
-                                                              it->Value));
-      }
-
-    if(this->Makefile->IsOn("APPLE"))
-      {
-      LinkImplementation const* impl = this->GetLinkImplementation(config,
-                                                                   this);
-      for(std::vector<std::string>::const_iterator
-          it = impl->Libraries.begin();
-          it != impl->Libraries.end(); ++it)
-        {
-        std::string libDir = cmSystemTools::CollapseFullPath(it->c_str());
-
-        static cmsys::RegularExpression
-          frameworkCheck("(.*\\.framework)(/Versions/[^/]+)?/[^/]+$");
-        if(!frameworkCheck.find(libDir))
-          {
-          continue;
-          }
-
-        libDir = frameworkCheck.match(1);
-
-        cmGeneratorExpression ge;
-        cmsys::auto_ptr<cmCompiledGeneratorExpression> cge =
-                  ge.Parse(libDir.c_str());
-        this->Internal
-                ->CachedLinkInterfaceIncludeDirectoriesEntries[config]
-                .push_back(new cmTargetInternals::TargetPropertyEntry(cge));
-        }
+                ge.Parse(libDir.c_str());
+      linkInterfaceIncludeDirectoriesEntries
+              .push_back(new cmTargetInternals::TargetPropertyEntry(cge));
       }
     }
 
   processIncludeDirectories(this,
-    this->Internal->CachedLinkInterfaceIncludeDirectoriesEntries[config],
+                            linkInterfaceIncludeDirectoriesEntries,
                             includes,
                             uniqueIncludes,
                             &dagChecker,
                             config,
                             debugIncludes);
 
-  if (!this->Makefile->IsGeneratingBuildSystem())
-    {
-    deleteAndClear(
-                this->Internal->CachedLinkInterfaceIncludeDirectoriesEntries);
-    }
-  else
-    {
-    this->Internal->CacheLinkInterfaceIncludeDirectoriesDone[config]
-                                                                      = true;
-    }
+  deleteAndClear(linkInterfaceIncludeDirectoriesEntries);
 
   return includes;
 }
@@ -2347,7 +2207,7 @@
 static void processCompileOptionsInternal(cmTarget const* tgt,
       const std::vector<cmTargetInternals::TargetPropertyEntry*> &entries,
       std::vector<std::string> &options,
-      std::set<std::string> &uniqueOptions,
+      UNORDERED_SET<std::string> &uniqueOptions,
       cmGeneratorExpressionDAGChecker *dagChecker,
       const std::string& config, bool debugOptions, const char *logName)
 {
@@ -2356,27 +2216,18 @@
   for (std::vector<cmTargetInternals::TargetPropertyEntry*>::const_iterator
       it = entries.begin(), end = entries.end(); it != end; ++it)
     {
-    bool cacheOptions = false;
-    std::vector<std::string> entryOptions = (*it)->CachedEntries;
-    if(entryOptions.empty())
-      {
-      cmSystemTools::ExpandListArgument((*it)->ge->Evaluate(mf,
-                                                config,
-                                                false,
-                                                tgt,
-                                                dagChecker),
-                                      entryOptions);
-      if (mf->IsGeneratingBuildSystem()
-          && !(*it)->ge->GetHadContextSensitiveCondition())
-        {
-        cacheOptions = true;
-        }
-      }
+    std::vector<std::string> entryOptions;
+    cmSystemTools::ExpandListArgument((*it)->ge->Evaluate(mf,
+                                              config,
+                                              false,
+                                              tgt,
+                                              dagChecker),
+                                    entryOptions);
     std::string usedOptions;
     for(std::vector<std::string>::iterator
           li = entryOptions.begin(); li != entryOptions.end(); ++li)
       {
-      std::string opt = *li;
+      std::string const& opt = *li;
 
       if(uniqueOptions.insert(opt).second)
         {
@@ -2387,10 +2238,6 @@
           }
         }
       }
-    if (cacheOptions)
-      {
-      (*it)->CachedEntries = entryOptions;
-      }
     if (!usedOptions.empty())
       {
       mf->GetCMakeInstance()->IssueMessage(cmake::LOG,
@@ -2406,7 +2253,7 @@
 static void processCompileOptions(cmTarget const* tgt,
       const std::vector<cmTargetInternals::TargetPropertyEntry*> &entries,
       std::vector<std::string> &options,
-      std::set<std::string> &uniqueOptions,
+      UNORDERED_SET<std::string> &uniqueOptions,
       cmGeneratorExpressionDAGChecker *dagChecker,
       const std::string& config, bool debugOptions)
 {
@@ -2443,7 +2290,7 @@
 void cmTarget::GetCompileOptions(std::vector<std::string> &result,
                                  const std::string& config) const
 {
-  std::set<std::string> uniqueOptions;
+  UNORDERED_SET<std::string> uniqueOptions;
 
   cmGeneratorExpressionDAGChecker dagChecker(this->GetName(),
                                              "COMPILE_OPTIONS", 0, 0);
@@ -2475,72 +2322,29 @@
                             config,
                             debugOptions);
 
-  if (!this->Internal->CacheLinkInterfaceCompileOptionsDone[config])
-    {
-    for (std::vector<cmValueWithOrigin>::const_iterator
-        it = this->Internal->LinkImplementationPropertyEntries.begin(),
-        end = this->Internal->LinkImplementationPropertyEntries.end();
-        it != end; ++it)
-      {
-      if (!cmGeneratorExpression::IsValidTargetName(it->Value)
-          && cmGeneratorExpression::Find(it->Value) == std::string::npos)
-        {
-        continue;
-        }
-      {
-      cmGeneratorExpression ge;
-      cmsys::auto_ptr<cmCompiledGeneratorExpression> cge =
-                                                        ge.Parse(it->Value);
-      std::string targetResult = cge->Evaluate(this->Makefile, config,
-                                        false, this, 0, 0);
-      if (!this->Makefile->FindTargetToUse(targetResult))
-        {
-        continue;
-        }
-      }
-      std::string optionGenex = "$<TARGET_PROPERTY:" +
-                              it->Value + ",INTERFACE_COMPILE_OPTIONS>";
-      if (cmGeneratorExpression::Find(it->Value) != std::string::npos)
-        {
-        // Because it->Value is a generator expression, ensure that it
-        // evaluates to the non-empty string before being used in the
-        // TARGET_PROPERTY expression.
-        optionGenex = "$<$<BOOL:" + it->Value + ">:" + optionGenex + ">";
-        }
-      cmGeneratorExpression ge(&it->Backtrace);
-      cmsys::auto_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(
-                                                                optionGenex);
+  std::vector<cmTargetInternals::TargetPropertyEntry*>
+    linkInterfaceCompileOptionsEntries;
 
-      this->Internal
-        ->CachedLinkInterfaceCompileOptionsEntries[config].push_back(
-                        new cmTargetInternals::TargetPropertyEntry(cge,
-                                                              it->Value));
-      }
-    }
+  this->Internal->AddInterfaceEntries(
+    this, config, "INTERFACE_COMPILE_OPTIONS",
+    linkInterfaceCompileOptionsEntries);
 
   processCompileOptions(this,
-    this->Internal->CachedLinkInterfaceCompileOptionsEntries[config],
+                        linkInterfaceCompileOptionsEntries,
                             result,
                             uniqueOptions,
                             &dagChecker,
                             config,
                             debugOptions);
 
-  if (!this->Makefile->IsGeneratingBuildSystem())
-    {
-    deleteAndClear(this->Internal->CachedLinkInterfaceCompileOptionsEntries);
-    }
-  else
-    {
-    this->Internal->CacheLinkInterfaceCompileOptionsDone[config] = true;
-    }
+  deleteAndClear(linkInterfaceCompileOptionsEntries);
 }
 
 //----------------------------------------------------------------------------
 static void processCompileDefinitions(cmTarget const* tgt,
       const std::vector<cmTargetInternals::TargetPropertyEntry*> &entries,
       std::vector<std::string> &options,
-      std::set<std::string> &uniqueOptions,
+      UNORDERED_SET<std::string> &uniqueOptions,
       cmGeneratorExpressionDAGChecker *dagChecker,
       const std::string& config, bool debugOptions)
 {
@@ -2553,7 +2357,7 @@
 void cmTarget::GetCompileDefinitions(std::vector<std::string> &list,
                                             const std::string& config) const
 {
-  std::set<std::string> uniqueOptions;
+  UNORDERED_SET<std::string> uniqueOptions;
 
   cmGeneratorExpressionDAGChecker dagChecker(this->GetName(),
                                              "COMPILE_DEFINITIONS", 0, 0);
@@ -2585,109 +2389,61 @@
                             config,
                             debugDefines);
 
-  if (!this->Internal->CacheLinkInterfaceCompileDefinitionsDone[config])
+  std::vector<cmTargetInternals::TargetPropertyEntry*>
+    linkInterfaceCompileDefinitionsEntries;
+  this->Internal->AddInterfaceEntries(
+    this, config, "INTERFACE_COMPILE_DEFINITIONS",
+    linkInterfaceCompileDefinitionsEntries);
+  if (!config.empty())
     {
-    for (std::vector<cmValueWithOrigin>::const_iterator
-        it = this->Internal->LinkImplementationPropertyEntries.begin(),
-        end = this->Internal->LinkImplementationPropertyEntries.end();
-        it != end; ++it)
+    std::string configPropName = "COMPILE_DEFINITIONS_"
+                                        + cmSystemTools::UpperCase(config);
+    const char *configProp = this->GetProperty(configPropName);
+    if (configProp)
       {
-      if (!cmGeneratorExpression::IsValidTargetName(it->Value)
-          && cmGeneratorExpression::Find(it->Value) == std::string::npos)
+      switch(this->Makefile->GetPolicyStatus(cmPolicies::CMP0043))
         {
-        continue;
-        }
-      {
-      cmGeneratorExpression ge;
-      cmsys::auto_ptr<cmCompiledGeneratorExpression> cge =
-                                                        ge.Parse(it->Value);
-      std::string targetResult = cge->Evaluate(this->Makefile, config,
-                                        false, this, 0, 0);
-      if (!this->Makefile->FindTargetToUse(targetResult))
-        {
-        continue;
-        }
-      }
-      std::string defsGenex = "$<TARGET_PROPERTY:" +
-                              it->Value + ",INTERFACE_COMPILE_DEFINITIONS>";
-      if (cmGeneratorExpression::Find(it->Value) != std::string::npos)
-        {
-        // Because it->Value is a generator expression, ensure that it
-        // evaluates to the non-empty string before being used in the
-        // TARGET_PROPERTY expression.
-        defsGenex = "$<$<BOOL:" + it->Value + ">:" + defsGenex + ">";
-        }
-      cmGeneratorExpression ge(&it->Backtrace);
-      cmsys::auto_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(
-                                                                defsGenex);
-
-      this->Internal
-        ->CachedLinkInterfaceCompileDefinitionsEntries[config].push_back(
-                        new cmTargetInternals::TargetPropertyEntry(cge,
-                                                              it->Value));
-      }
-    if (!config.empty())
-      {
-      std::string configPropName = "COMPILE_DEFINITIONS_"
-                                          + cmSystemTools::UpperCase(config);
-      const char *configProp = this->GetProperty(configPropName);
-      if (configProp)
-        {
-        switch(this->Makefile->GetPolicyStatus(cmPolicies::CMP0043))
+        case cmPolicies::WARN:
           {
-          case cmPolicies::WARN:
-            {
-            cmOStringStream e;
-            e << this->Makefile->GetCMakeInstance()->GetPolicies()
-                     ->GetPolicyWarning(cmPolicies::CMP0043);
-            this->Makefile->IssueMessage(cmake::AUTHOR_WARNING,
-                                         e.str());
-            }
-          case cmPolicies::OLD:
-            {
-            cmGeneratorExpression ge;
-            cmsys::auto_ptr<cmCompiledGeneratorExpression> cge =
-                                                        ge.Parse(configProp);
-            this->Internal
-              ->CachedLinkInterfaceCompileDefinitionsEntries[config]
-                  .push_back(new cmTargetInternals::TargetPropertyEntry(cge));
-            }
-            break;
-          case cmPolicies::NEW:
-          case cmPolicies::REQUIRED_ALWAYS:
-          case cmPolicies::REQUIRED_IF_USED:
-            break;
+          cmOStringStream e;
+          e << this->Makefile->GetCMakeInstance()->GetPolicies()
+                   ->GetPolicyWarning(cmPolicies::CMP0043);
+          this->Makefile->IssueMessage(cmake::AUTHOR_WARNING,
+                                       e.str());
           }
+        case cmPolicies::OLD:
+          {
+          cmGeneratorExpression ge;
+          cmsys::auto_ptr<cmCompiledGeneratorExpression> cge =
+                                                      ge.Parse(configProp);
+          linkInterfaceCompileDefinitionsEntries
+                .push_back(new cmTargetInternals::TargetPropertyEntry(cge));
+          }
+          break;
+        case cmPolicies::NEW:
+        case cmPolicies::REQUIRED_ALWAYS:
+        case cmPolicies::REQUIRED_IF_USED:
+          break;
         }
       }
-
     }
 
   processCompileDefinitions(this,
-    this->Internal->CachedLinkInterfaceCompileDefinitionsEntries[config],
+                            linkInterfaceCompileDefinitionsEntries,
                             list,
                             uniqueOptions,
                             &dagChecker,
                             config,
                             debugDefines);
 
-  if (!this->Makefile->IsGeneratingBuildSystem())
-    {
-    deleteAndClear(this->Internal
-                              ->CachedLinkInterfaceCompileDefinitionsEntries);
-    }
-  else
-    {
-    this->Internal->CacheLinkInterfaceCompileDefinitionsDone[config]
-                                                                      = true;
-    }
+  deleteAndClear(linkInterfaceCompileDefinitionsEntries);
 }
 
 //----------------------------------------------------------------------------
 static void processCompileFeatures(cmTarget const* tgt,
       const std::vector<cmTargetInternals::TargetPropertyEntry*> &entries,
       std::vector<std::string> &options,
-      std::set<std::string> &uniqueOptions,
+      UNORDERED_SET<std::string> &uniqueOptions,
       cmGeneratorExpressionDAGChecker *dagChecker,
       const std::string& config, bool debugOptions)
 {
@@ -2699,7 +2455,7 @@
 void cmTarget::GetCompileFeatures(std::vector<std::string> &result,
                                   const std::string& config) const
 {
-  std::set<std::string> uniqueFeatures;
+  UNORDERED_SET<std::string> uniqueFeatures;
 
   cmGeneratorExpressionDAGChecker dagChecker(this->GetName(),
                                              "COMPILE_FEATURES",
@@ -2732,65 +2488,21 @@
                             config,
                             debugFeatures);
 
-  if (!this->Internal->CacheLinkInterfaceCompileFeaturesDone[config])
-    {
-    for (std::vector<cmValueWithOrigin>::const_iterator
-        it = this->Internal->LinkImplementationPropertyEntries.begin(),
-        end = this->Internal->LinkImplementationPropertyEntries.end();
-        it != end; ++it)
-      {
-      if (!cmGeneratorExpression::IsValidTargetName(it->Value)
-          && cmGeneratorExpression::Find(it->Value) == std::string::npos)
-        {
-        continue;
-        }
-      {
-      cmGeneratorExpression ge;
-      cmsys::auto_ptr<cmCompiledGeneratorExpression> cge =
-                                                        ge.Parse(it->Value);
-      std::string targetResult = cge->Evaluate(this->Makefile, config,
-                                        false, this, 0, 0);
-      if (!this->Makefile->FindTargetToUse(targetResult))
-        {
-        continue;
-        }
-      }
-      std::string featureGenex = "$<TARGET_PROPERTY:" +
-                              it->Value + ",INTERFACE_COMPILE_FEATURES>";
-      if (cmGeneratorExpression::Find(it->Value) != std::string::npos)
-        {
-        // Because it->Value is a generator expression, ensure that it
-        // evaluates to the non-empty string before being used in the
-        // TARGET_PROPERTY expression.
-        featureGenex = "$<$<BOOL:" + it->Value + ">:" + featureGenex + ">";
-        }
-      cmGeneratorExpression ge(&it->Backtrace);
-      cmsys::auto_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(
-                                                                featureGenex);
-
-      this->Internal
-        ->CachedLinkInterfaceCompileFeaturesEntries[config].push_back(
-                        new cmTargetInternals::TargetPropertyEntry(cge,
-                                                              it->Value));
-      }
-    }
+  std::vector<cmTargetInternals::TargetPropertyEntry*>
+    linkInterfaceCompileFeaturesEntries;
+  this->Internal->AddInterfaceEntries(
+    this, config, "INTERFACE_COMPILE_FEATURES",
+    linkInterfaceCompileFeaturesEntries);
 
   processCompileFeatures(this,
-    this->Internal->CachedLinkInterfaceCompileFeaturesEntries[config],
+                         linkInterfaceCompileFeaturesEntries,
                             result,
                             uniqueFeatures,
                             &dagChecker,
                             config,
                             debugFeatures);
 
-  if (!this->Makefile->IsGeneratingBuildSystem())
-    {
-    deleteAndClear(this->Internal->CachedLinkInterfaceCompileFeaturesEntries);
-    }
-  else
-    {
-    this->Internal->CacheLinkInterfaceCompileFeaturesDone[config] = true;
-    }
+  deleteAndClear(linkInterfaceCompileFeaturesEntries);
 }
 
 //----------------------------------------------------------------------------
@@ -3068,16 +2780,11 @@
 
   // Now handle the deprecated build-time configuration location.
   location = this->GetDirectory();
-  if(!location.empty())
-    {
-    location += "/";
-    }
   const char* cfgid = this->Makefile->GetDefinition("CMAKE_CFG_INTDIR");
   if(cfgid && strcmp(cfgid, ".") != 0)
     {
     location += "/";
     location += cfgid;
-    location += "/";
     }
 
   if(this->IsAppBundleOnApple())
@@ -3198,6 +2905,22 @@
 }
 
 //----------------------------------------------------------------------------
+static void MakePropertyList(std::string& output,
+    std::vector<cmTargetInternals::TargetPropertyEntry*> const& values)
+{
+  output = "";
+  std::string sep;
+  for (std::vector<cmTargetInternals::TargetPropertyEntry*>::const_iterator
+       it = values.begin(), end = values.end();
+       it != end; ++it)
+    {
+    output += sep;
+    output += (*it)->ge->GetInput();
+    sep = ";";
+    }
+}
+
+//----------------------------------------------------------------------------
 const char *cmTarget::GetProperty(const std::string& prop) const
 {
   return this->GetProperty(prop, this->Makefile);
@@ -3217,11 +2940,6 @@
     return 0;
     }
 
-  if (prop == "NAME")
-    {
-    return this->GetName().c_str();
-    }
-
   // Watch for special "computed" properties that are dependent on
   // other properties or variables.  Always recompute them.
   if(this->GetType() == cmTarget::EXECUTABLE ||
@@ -3230,7 +2948,8 @@
      this->GetType() == cmTarget::MODULE_LIBRARY ||
      this->GetType() == cmTarget::UNKNOWN_LIBRARY)
     {
-    if(prop == "LOCATION")
+    static const std::string propLOCATION = "LOCATION";
+    if(prop == propLOCATION)
       {
       if (!this->HandleLocationPropertyPolicy(context))
         {
@@ -3246,12 +2965,12 @@
       // cannot take into account the per-configuration name of the
       // target because the configuration type may not be known at
       // CMake time.
-      this->Properties.SetProperty("LOCATION", this->GetLocationForBuild(),
+      this->Properties.SetProperty(propLOCATION, this->GetLocationForBuild(),
                                    cmProperty::TARGET);
       }
 
     // Support "LOCATION_<CONFIG>".
-    if(cmHasLiteralPrefix(prop, "LOCATION_"))
+    else if(cmHasLiteralPrefix(prop, "LOCATION_"))
       {
       if (!this->HandleLocationPropertyPolicy(context))
         {
@@ -3263,7 +2982,7 @@
                                    cmProperty::TARGET);
       }
     // Support "<CONFIG>_LOCATION".
-    if(cmHasLiteralSuffix(prop, "_LOCATION"))
+    else if(cmHasLiteralSuffix(prop, "_LOCATION"))
       {
       std::string configName(prop.c_str(), prop.size() - 9);
       if(configName != "IMPORTED")
@@ -3278,198 +2997,210 @@
         }
       }
     }
-  if(prop == "INCLUDE_DIRECTORIES")
+  static UNORDERED_SET<std::string> specialProps;
+#define MAKE_STATIC_PROP(PROP) \
+  static const std::string prop##PROP = #PROP
+  MAKE_STATIC_PROP(LINK_LIBRARIES);
+  MAKE_STATIC_PROP(TYPE);
+  MAKE_STATIC_PROP(INCLUDE_DIRECTORIES);
+  MAKE_STATIC_PROP(COMPILE_FEATURES);
+  MAKE_STATIC_PROP(COMPILE_OPTIONS);
+  MAKE_STATIC_PROP(COMPILE_DEFINITIONS);
+  MAKE_STATIC_PROP(IMPORTED);
+  MAKE_STATIC_PROP(NAME);
+  MAKE_STATIC_PROP(SOURCES);
+#undef MAKE_STATIC_PROP
+  if(specialProps.empty())
     {
-    static std::string output;
-    output = "";
-    std::string sep;
-    typedef cmTargetInternals::TargetPropertyEntry
-                                TargetPropertyEntry;
-    for (std::vector<TargetPropertyEntry*>::const_iterator
-        it = this->Internal->IncludeDirectoriesEntries.begin(),
-        end = this->Internal->IncludeDirectoriesEntries.end();
-        it != end; ++it)
-      {
-      output += sep;
-      output += (*it)->ge->GetInput();
-      sep = ";";
-      }
-    return output.c_str();
+    specialProps.insert(propLINK_LIBRARIES);
+    specialProps.insert(propTYPE);
+    specialProps.insert(propINCLUDE_DIRECTORIES);
+    specialProps.insert(propCOMPILE_FEATURES);
+    specialProps.insert(propCOMPILE_OPTIONS);
+    specialProps.insert(propCOMPILE_DEFINITIONS);
+    specialProps.insert(propIMPORTED);
+    specialProps.insert(propNAME);
+    specialProps.insert(propSOURCES);
     }
-  if(prop == "COMPILE_OPTIONS")
+  if(specialProps.count(prop))
     {
-    static std::string output;
-    output = "";
-    std::string sep;
-    typedef cmTargetInternals::TargetPropertyEntry
-                                TargetPropertyEntry;
-    for (std::vector<TargetPropertyEntry*>::const_iterator
-        it = this->Internal->CompileOptionsEntries.begin(),
-        end = this->Internal->CompileOptionsEntries.end();
-        it != end; ++it)
+    if(prop == propLINK_LIBRARIES)
       {
-      output += sep;
-      output += (*it)->ge->GetInput();
-      sep = ";";
-      }
-    return output.c_str();
-    }
-  if(prop == "COMPILE_FEATURES")
-    {
-    static std::string output;
-    output = "";
-    std::string sep;
-    typedef cmTargetInternals::TargetPropertyEntry
-                                TargetPropertyEntry;
-    for (std::vector<TargetPropertyEntry*>::const_iterator
-        it = this->Internal->CompileFeaturesEntries.begin(),
-        end = this->Internal->CompileFeaturesEntries.end();
-        it != end; ++it)
-      {
-      output += sep;
-      output += (*it)->ge->GetInput();
-      sep = ";";
-      }
-    return output.c_str();
-    }
-  if(prop == "COMPILE_DEFINITIONS")
-    {
-    static std::string output;
-    output = "";
-    std::string sep;
-    typedef cmTargetInternals::TargetPropertyEntry
-                                TargetPropertyEntry;
-    for (std::vector<TargetPropertyEntry*>::const_iterator
-        it = this->Internal->CompileDefinitionsEntries.begin(),
-        end = this->Internal->CompileDefinitionsEntries.end();
-        it != end; ++it)
-      {
-      output += sep;
-      output += (*it)->ge->GetInput();
-      sep = ";";
-      }
-    return output.c_str();
-    }
-  if(prop == "LINK_LIBRARIES")
-    {
-    static std::string output;
-    output = "";
-    std::string sep;
-    for (std::vector<cmValueWithOrigin>::const_iterator
-        it = this->Internal->LinkImplementationPropertyEntries.begin(),
-        end = this->Internal->LinkImplementationPropertyEntries.end();
-        it != end; ++it)
-      {
-      output += sep;
-      output += it->Value;
-      sep = ";";
-      }
-    return output.c_str();
-    }
-
-  if (prop == "IMPORTED")
-    {
-    return this->IsImported()?"TRUE":"FALSE";
-    }
-
-  if(prop == "SOURCES")
-    {
-    cmOStringStream ss;
-    const char* sep = "";
-    typedef cmTargetInternals::TargetPropertyEntry
-                                TargetPropertyEntry;
-    for(std::vector<TargetPropertyEntry*>::const_iterator
-          i = this->Internal->SourceEntries.begin();
-        i != this->Internal->SourceEntries.end(); ++i)
-      {
-      std::string entry = (*i)->ge->GetInput();
-
-      std::vector<std::string> files;
-      cmSystemTools::ExpandListArgument(entry, files);
-      for (std::vector<std::string>::const_iterator
-          li = files.begin(); li != files.end(); ++li)
+      if (this->Internal->LinkImplementationPropertyEntries.empty())
         {
-        if(cmHasLiteralPrefix(*li, "$<TARGET_OBJECTS:") &&
-            (*li)[li->size() - 1] == '>')
+        return 0;
+        }
+
+      static std::string output;
+      output = "";
+      std::string sep;
+      for (std::vector<cmValueWithOrigin>::const_iterator
+          it = this->Internal->LinkImplementationPropertyEntries.begin(),
+          end = this->Internal->LinkImplementationPropertyEntries.end();
+          it != end; ++it)
+        {
+        output += sep;
+        output += it->Value;
+        sep = ";";
+        }
+      return output.c_str();
+      }
+    // the type property returns what type the target is
+    else if (prop == propTYPE)
+      {
+      return cmTarget::GetTargetTypeName(this->GetType());
+      }
+    else if(prop == propINCLUDE_DIRECTORIES)
+      {
+      if (this->Internal->IncludeDirectoriesEntries.empty())
+        {
+        return 0;
+        }
+
+      static std::string output;
+      MakePropertyList(output, this->Internal->IncludeDirectoriesEntries);
+      return output.c_str();
+      }
+    else if(prop == propCOMPILE_FEATURES)
+      {
+      if (this->Internal->CompileFeaturesEntries.empty())
+        {
+        return 0;
+        }
+
+      static std::string output;
+      MakePropertyList(output, this->Internal->CompileFeaturesEntries);
+      return output.c_str();
+      }
+    else if(prop == propCOMPILE_OPTIONS)
+      {
+      if (this->Internal->CompileOptionsEntries.empty())
+        {
+        return 0;
+        }
+
+      static std::string output;
+      MakePropertyList(output, this->Internal->CompileOptionsEntries);
+      return output.c_str();
+      }
+    else if(prop == propCOMPILE_DEFINITIONS)
+      {
+      if (this->Internal->CompileDefinitionsEntries.empty())
+        {
+        return 0;
+        }
+
+      static std::string output;
+      MakePropertyList(output, this->Internal->CompileDefinitionsEntries);
+      return output.c_str();
+      }
+    else if (prop == propIMPORTED)
+      {
+      return this->IsImported()?"TRUE":"FALSE";
+      }
+    else if (prop == propNAME)
+      {
+      return this->GetName().c_str();
+      }
+    else if(prop == propSOURCES)
+      {
+      if (this->Internal->SourceEntries.empty())
+        {
+        return 0;
+        }
+
+      cmOStringStream ss;
+      const char* sep = "";
+      typedef cmTargetInternals::TargetPropertyEntry
+                                  TargetPropertyEntry;
+      for(std::vector<TargetPropertyEntry*>::const_iterator
+            i = this->Internal->SourceEntries.begin();
+          i != this->Internal->SourceEntries.end(); ++i)
+        {
+        std::string entry = (*i)->ge->GetInput();
+
+        std::vector<std::string> files;
+        cmSystemTools::ExpandListArgument(entry, files);
+        for (std::vector<std::string>::const_iterator
+            li = files.begin(); li != files.end(); ++li)
           {
-          std::string objLibName = li->substr(17, li->size()-18);
+          if(cmHasLiteralPrefix(*li, "$<TARGET_OBJECTS:") &&
+              (*li)[li->size() - 1] == '>')
+            {
+            std::string objLibName = li->substr(17, li->size()-18);
 
-          if (cmGeneratorExpression::Find(objLibName) != std::string::npos)
-            {
-            ss << sep;
-            sep = ";";
-            ss << *li;
-            continue;
-            }
+            if (cmGeneratorExpression::Find(objLibName) != std::string::npos)
+              {
+              ss << sep;
+              sep = ";";
+              ss << *li;
+              continue;
+              }
 
-          bool addContent = false;
-          bool noMessage = true;
-          cmOStringStream e;
-          cmake::MessageType messageType = cmake::AUTHOR_WARNING;
-          switch(context->GetPolicyStatus(cmPolicies::CMP0051))
-            {
-            case cmPolicies::WARN:
-              e << (this->Makefile->GetPolicies()
-                    ->GetPolicyWarning(cmPolicies::CMP0051)) << "\n";
-              noMessage = false;
-            case cmPolicies::OLD:
-              break;
-            case cmPolicies::REQUIRED_ALWAYS:
-            case cmPolicies::REQUIRED_IF_USED:
-            case cmPolicies::NEW:
-              addContent = true;
+            bool addContent = false;
+            bool noMessage = true;
+            cmOStringStream e;
+            cmake::MessageType messageType = cmake::AUTHOR_WARNING;
+            switch(context->GetPolicyStatus(cmPolicies::CMP0051))
+              {
+              case cmPolicies::WARN:
+                e << (this->Makefile->GetPolicies()
+                      ->GetPolicyWarning(cmPolicies::CMP0051)) << "\n";
+                noMessage = false;
+              case cmPolicies::OLD:
+                break;
+              case cmPolicies::REQUIRED_ALWAYS:
+              case cmPolicies::REQUIRED_IF_USED:
+              case cmPolicies::NEW:
+                addContent = true;
+              }
+            if (!noMessage)
+              {
+              e << "Target \"" << this->Name << "\" contains "
+              "$<TARGET_OBJECTS> generator expression in its sources list.  "
+              "This content was not previously part of the SOURCES property "
+              "when that property was read at configure time.  Code reading "
+              "that property needs to be adapted to ignore the generator "
+              "expression using the string(GENEX_STRIP) command.";
+              context->IssueMessage(messageType, e.str());
+              }
+            if (addContent)
+              {
+              ss << sep;
+              sep = ";";
+              ss << *li;
+              }
             }
-          if (!noMessage)
-            {
-            e << "Target \"" << this->Name << "\" contains $<TARGET_OBJECTS> "
-            "generator expression in its sources list.  This content was not "
-            "previously part of the SOURCES property when that property was "
-            "read at configure time.  Code reading that property needs to be "
-            "adapted to ignore the generator expression using the "
-            "string(GENEX_STRIP) command.";
-            context->IssueMessage(messageType, e.str());
-            }
-          if (addContent)
+          else if (cmGeneratorExpression::Find(*li) == std::string::npos)
             {
             ss << sep;
             sep = ";";
             ss << *li;
             }
-          }
-        else if (cmGeneratorExpression::Find(*li) == std::string::npos)
-          {
-          ss << sep;
-          sep = ";";
-          ss << *li;
-          }
-        else
-          {
-          cmSourceFile *sf = this->Makefile->GetOrCreateSource(*li);
-          // Construct what is known about this source file location.
-          cmSourceFileLocation const& location = sf->GetLocation();
-          std::string sname = location.GetDirectory();
-          if(!sname.empty())
+          else
             {
-            sname += "/";
-            }
-          sname += location.GetName();
+            cmSourceFile *sf = this->Makefile->GetOrCreateSource(*li);
+            // Construct what is known about this source file location.
+            cmSourceFileLocation const& location = sf->GetLocation();
+            std::string sname = location.GetDirectory();
+            if(!sname.empty())
+              {
+              sname += "/";
+              }
+            sname += location.GetName();
 
-          ss << sep;
-          sep = ";";
-          // Append this list entry.
-          ss << sname;
+            ss << sep;
+            sep = ";";
+            // Append this list entry.
+            ss << sname;
+            }
           }
         }
+      this->Properties.SetProperty("SOURCES", ss.str().c_str(),
+                                   cmProperty::TARGET);
       }
-    this->Properties.SetProperty("SOURCES", ss.str().c_str(),
-                                 cmProperty::TARGET);
     }
 
-  // the type property returns what type the target is
-  if (prop == "TYPE")
-    {
-    return cmTarget::GetTargetTypeName(this->GetType());
-    }
   bool chain = false;
   const char *retVal =
     this->Properties.GetPropertyValue(prop, cmProperty::TARGET, chain);
@@ -3492,19 +3223,17 @@
 public:
   cmTargetCollectLinkLanguages(cmTarget const* target,
                                const std::string& config,
-                               std::set<std::string>& languages,
+                               UNORDERED_SET<std::string>& languages,
                                cmTarget const* head):
     Config(config), Languages(languages), HeadTarget(head),
     Makefile(target->GetMakefile()), Target(target)
   { this->Visited.insert(target); }
 
-  void Visit(const std::string& name)
+  void Visit(cmLinkItem const& item)
     {
-    cmTarget *target = this->Makefile->FindTargetToUse(name);
-
-    if(!target)
+    if(!item.Target)
       {
-      if(name.find("::") != std::string::npos)
+      if(item.find("::") != std::string::npos)
         {
         bool noMessage = false;
         cmake::MessageType messageType = cmake::FATAL_ERROR;
@@ -3530,7 +3259,7 @@
         if(!noMessage)
           {
           e << "Target \"" << this->Target->GetName()
-            << "\" links to target \"" << name
+            << "\" links to target \"" << item
             << "\" but the target was not found.  Perhaps a find_package() "
             "call is missing for an IMPORTED target, or an ALIAS target is "
             "missing?";
@@ -3541,13 +3270,13 @@
         }
       return;
       }
-    if(!this->Visited.insert(target).second)
+    if(!this->Visited.insert(item.Target).second)
       {
       return;
       }
 
     cmTarget::LinkInterface const* iface =
-      target->GetLinkInterface(this->Config, this->HeadTarget);
+      item.Target->GetLinkInterface(this->Config, this->HeadTarget);
     if(!iface) { return; }
 
     for(std::vector<std::string>::const_iterator
@@ -3556,7 +3285,7 @@
       this->Languages.insert(*li);
       }
 
-    for(std::vector<std::string>::const_iterator
+    for(std::vector<cmLinkItem>::const_iterator
           li = iface->Libraries.begin(); li != iface->Libraries.end(); ++li)
       {
       this->Visit(*li);
@@ -3564,7 +3293,7 @@
     }
 private:
   std::string Config;
-  std::set<std::string>& Languages;
+  UNORDERED_SET<std::string>& Languages;
   cmTarget const* HeadTarget;
   cmMakefile* Makefile;
   const cmTarget* Target;
@@ -3572,25 +3301,22 @@
 };
 
 //----------------------------------------------------------------------------
-std::string cmTarget::GetLinkerLanguage(const std::string& config,
-                                        cmTarget const* head) const
+std::string cmTarget::GetLinkerLanguage(const std::string& config) const
 {
-  cmTarget const* headTarget = head ? head : this;
-  return this->GetLinkClosure(config, headTarget)->LinkerLanguage;
+  return this->GetLinkClosure(config)->LinkerLanguage;
 }
 
 //----------------------------------------------------------------------------
-cmTarget::LinkClosure const* cmTarget::GetLinkClosure(
-                                                  const std::string& config,
-                                                  cmTarget const* head) const
+cmTarget::LinkClosure const*
+cmTarget::GetLinkClosure(const std::string& config) const
 {
-  TargetConfigPair key(head, cmSystemTools::UpperCase(config));
+  std::string key(cmSystemTools::UpperCase(config));
   cmTargetInternals::LinkClosureMapType::iterator
     i = this->Internal->LinkClosureMap.find(key);
   if(i == this->Internal->LinkClosureMap.end())
     {
     LinkClosure lc;
-    this->ComputeLinkClosure(config, lc, head);
+    this->ComputeLinkClosure(config, lc);
     cmTargetInternals::LinkClosureMapType::value_type entry(key, lc);
     i = this->Internal->LinkClosureMap.insert(entry).first;
     }
@@ -3604,7 +3330,7 @@
   cmTarget const* Target;
   cmMakefile* Makefile;
   cmGlobalGenerator* GG;
-  std::set<std::string> Preferred;
+  UNORDERED_SET<std::string> Preferred;
 public:
   cmTargetSelectLinker(cmTarget const* target): Preference(0), Target(target)
     {
@@ -3636,7 +3362,7 @@
       e << "Target " << this->Target->GetName()
         << " contains multiple languages with the highest linker preference"
         << " (" << this->Preference << "):\n";
-      for(std::set<std::string>::const_iterator
+      for(UNORDERED_SET<std::string>::const_iterator
             li = this->Preferred.begin(); li != this->Preferred.end(); ++li)
         {
         e << "  " << *li << "\n";
@@ -3651,12 +3377,12 @@
 };
 
 //----------------------------------------------------------------------------
-void cmTarget::ComputeLinkClosure(const std::string& config, LinkClosure& lc,
-                                  cmTarget const* head) const
+void cmTarget::ComputeLinkClosure(const std::string& config,
+                                  LinkClosure& lc) const
 {
   // Get languages built in this target.
-  std::set<std::string> languages;
-  LinkImplementation const* impl = this->GetLinkImplementation(config, head);
+  UNORDERED_SET<std::string> languages;
+  LinkImplementation const* impl = this->GetLinkImplementation(config);
   for(std::vector<std::string>::const_iterator li = impl->Languages.begin();
       li != impl->Languages.end(); ++li)
     {
@@ -3664,15 +3390,16 @@
     }
 
   // Add interface languages from linked targets.
-  cmTargetCollectLinkLanguages cll(this, config, languages, head);
-  for(std::vector<std::string>::const_iterator li = impl->Libraries.begin();
+  cmTargetCollectLinkLanguages cll(this, config, languages, this);
+  for(std::vector<cmLinkImplItem>::const_iterator
+        li = impl->Libraries.begin();
       li != impl->Libraries.end(); ++li)
     {
     cll.Visit(*li);
     }
 
   // Store the transitive closure of languages.
-  for(std::set<std::string>::const_iterator li = languages.begin();
+  for(UNORDERED_SET<std::string>::const_iterator li = languages.begin();
       li != languages.end(); ++li)
     {
     lc.Languages.push_back(*li);
@@ -3700,7 +3427,7 @@
       }
 
     // Now consider languages that propagate from linked targets.
-    for(std::set<std::string>::const_iterator sit = languages.begin();
+    for(UNORDERED_SET<std::string>::const_iterator sit = languages.begin();
         sit != languages.end(); ++sit)
       {
       std::string propagates = "CMAKE_"+*sit+"_LINKER_PREFERENCE_PROPAGATES";
@@ -3715,6 +3442,51 @@
 }
 
 //----------------------------------------------------------------------------
+void cmTarget::ExpandLinkItems(std::string const& prop,
+                               std::string const& value,
+                               std::string const& config,
+                               cmTarget const* headTarget,
+                               bool usage_requirements_only,
+                               std::vector<cmLinkItem>& items,
+                               bool& hadHeadSensitiveCondition) const
+{
+  cmGeneratorExpression ge;
+  cmGeneratorExpressionDAGChecker dagChecker(this->GetName(), prop, 0, 0);
+  // The $<LINK_ONLY> expression may be in a link interface to specify private
+  // link dependencies that are otherwise excluded from usage requirements.
+  if(usage_requirements_only)
+    {
+    dagChecker.SetTransitivePropertiesOnly();
+    }
+  std::vector<std::string> libs;
+  cmsys::auto_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(value);
+  cmSystemTools::ExpandListArgument(cge->Evaluate(
+                                      this->Makefile,
+                                      config,
+                                      false,
+                                      headTarget,
+                                      this, &dagChecker), libs);
+  this->LookupLinkItems(libs, items);
+  hadHeadSensitiveCondition = cge->GetHadHeadSensitiveCondition();
+}
+
+//----------------------------------------------------------------------------
+void cmTarget::LookupLinkItems(std::vector<std::string> const& names,
+                               std::vector<cmLinkItem>& items) const
+{
+  for(std::vector<std::string>::const_iterator i = names.begin();
+      i != names.end(); ++i)
+    {
+    std::string name = this->CheckCMP0004(*i);
+    if(name == this->GetName() || name.empty())
+      {
+      continue;
+      }
+    items.push_back(cmLinkItem(name, this->FindTargetToLink(name)));
+    }
+}
+
+//----------------------------------------------------------------------------
 const char* cmTarget::GetSuffixVariableInternal(bool implib) const
 {
   switch(this->GetType())
@@ -3732,7 +3504,10 @@
     case cmTarget::EXECUTABLE:
       return (implib
               ? "CMAKE_IMPORT_LIBRARY_SUFFIX"
-              : "CMAKE_EXECUTABLE_SUFFIX");
+                // Android GUI application packages store the native
+                // binary as a shared library.
+              : (this->IsAndroid && this->GetPropertyAsBool("ANDROID_GUI")?
+                 "CMAKE_SHARED_LIBRARY_SUFFIX" : "CMAKE_EXECUTABLE_SUFFIX"));
     default:
       break;
     }
@@ -3756,7 +3531,12 @@
               ? "CMAKE_IMPORT_LIBRARY_PREFIX"
               : "CMAKE_SHARED_MODULE_PREFIX");
     case cmTarget::EXECUTABLE:
-      return (implib? "CMAKE_IMPORT_LIBRARY_PREFIX" : "");
+      return (implib
+              ? "CMAKE_IMPORT_LIBRARY_PREFIX"
+                // Android GUI application packages store the native
+                // binary as a shared library.
+              : (this->IsAndroid && this->GetPropertyAsBool("ANDROID_GUI")?
+                 "CMAKE_SHARED_LIBRARY_PREFIX" : ""));
     default:
       break;
     }
@@ -3845,8 +3625,7 @@
   return ((this->GetType() == cmTarget::SHARED_LIBRARY ||
            this->GetType() == cmTarget::MODULE_LIBRARY) &&
           !this->GetPropertyAsBool("NO_SONAME") &&
-          this->Makefile->GetSONameFlag(this->GetLinkerLanguage(config,
-                                                                this)));
+          this->Makefile->GetSONameFlag(this->GetLinkerLanguage(config)));
 }
 
 //----------------------------------------------------------------------------
@@ -3855,7 +3634,7 @@
   if(this->IsImported())
     {
     // Lookup the imported soname.
-    if(cmTarget::ImportInfo const* info = this->GetImportInfo(config, this))
+    if(cmTarget::ImportInfo const* info = this->GetImportInfo(config))
       {
       if(info->NoSOName)
         {
@@ -3923,7 +3702,7 @@
   else
     {
     // Lookup the imported soname.
-    if(cmTarget::ImportInfo const* info = this->GetImportInfo(config, this))
+    if(cmTarget::ImportInfo const* info = this->GetImportInfo(config))
       {
       if(!info->NoSOName && !info->SOName.empty())
         {
@@ -4009,7 +3788,7 @@
 {
   if(this->IsImported() && this->GetType() == cmTarget::SHARED_LIBRARY)
     {
-    if(cmTarget::ImportInfo const* info = this->GetImportInfo(config, this))
+    if(cmTarget::ImportInfo const* info = this->GetImportInfo(config))
       {
       return info->NoSOName;
       }
@@ -4133,7 +3912,7 @@
 cmTarget::ImportedGetFullPath(const std::string& config, bool implib) const
 {
   std::string result;
-  if(cmTarget::ImportInfo const* info = this->GetImportInfo(config, this))
+  if(cmTarget::ImportInfo const* info = this->GetImportInfo(config))
     {
     result = implib? info->ImportLibrary : info->Location;
     }
@@ -4219,7 +3998,7 @@
   const char* suffixVar = this->GetSuffixVariableInternal(implib);
 
   // Check for language-specific default prefix and suffix.
-  std::string ll = this->GetLinkerLanguage(config, this);
+  std::string ll = this->GetLinkerLanguage(config);
   if(!ll.empty())
     {
     if(!targetSuffix && suffixVar && *suffixVar)
@@ -4320,6 +4099,7 @@
   const char* version = this->GetProperty("VERSION");
   const char* soversion = this->GetProperty("SOVERSION");
   if(!this->HasSOName(config) ||
+     this->Makefile->IsOn("CMAKE_PLATFORM_NO_VERSIONED_SONAME") ||
      this->IsFrameworkOnApple())
     {
     // Versioning is supported only for shared libraries and modules,
@@ -4506,9 +4286,12 @@
     {
     return false;
     }
-  std::vector<std::string> libs;
-  this->GetDirectLinkLibraries(config, libs, this);
-  return !libs.empty();
+  if(LinkImplementationLibraries const* impl =
+     this->GetLinkImplementationLibraries(config))
+    {
+    return !impl->Libraries.empty();
+    }
+  return false;
 }
 
 //----------------------------------------------------------------------------
@@ -4557,7 +4340,7 @@
     }
 
   // Check for rpath support on this platform.
-  std::string ll = this->GetLinkerLanguage(config, this);
+  std::string ll = this->GetLinkerLanguage(config);
   if(!ll.empty())
     {
     std::string flagVar = "CMAKE_SHARED_LIBRARY_RUNTIME_";
@@ -4949,12 +4732,13 @@
 
 //----------------------------------------------------------------------------
 template<typename PropertyType>
-PropertyType getTypedProperty(cmTarget const* tgt, const char *prop,
+PropertyType getTypedProperty(cmTarget const* tgt, const std::string& prop,
                               PropertyType *);
 
 //----------------------------------------------------------------------------
 template<>
-bool getTypedProperty<bool>(cmTarget const* tgt, const char *prop, bool *)
+bool getTypedProperty<bool>(cmTarget const* tgt, const std::string& prop,
+                            bool *)
 {
   return tgt->GetPropertyAsBool(prop);
 }
@@ -4962,7 +4746,7 @@
 //----------------------------------------------------------------------------
 template<>
 const char *getTypedProperty<const char *>(cmTarget const* tgt,
-                                           const char *prop,
+                                           const std::string& prop,
                                            const char **)
 {
   return tgt->GetProperty(prop);
@@ -5201,7 +4985,7 @@
                                           CompatibleType t,
                                           PropertyType *)
 {
-  PropertyType propContent = getTypedProperty<PropertyType>(tgt, p.c_str(),
+  PropertyType propContent = getTypedProperty<PropertyType>(tgt, p,
                                                             0);
   const bool explicitlySet = tgt->GetProperties()
                                   .find(p)
@@ -5211,8 +4995,8 @@
   assert((impliedByUse ^ explicitlySet)
       || (!impliedByUse && !explicitlySet));
 
-  std::vector<cmTarget*> deps;
-  tgt->GetTransitiveTargetClosure(config, tgt, deps);
+  std::vector<cmTarget const*> const& deps =
+    tgt->GetLinkImplementationClosure(config);
 
   if(deps.empty())
     {
@@ -5237,7 +5021,8 @@
     report += "\" property not set.\n";
     }
 
-  for(std::vector<cmTarget*>::const_iterator li =
+  std::string interfaceProperty = "INTERFACE_" + p;
+  for(std::vector<cmTarget const*>::const_iterator li =
       deps.begin();
       li != deps.end(); ++li)
     {
@@ -5250,11 +5035,11 @@
     cmTarget const* theTarget = *li;
 
     const bool ifaceIsSet = theTarget->GetProperties()
-                            .find("INTERFACE_" + p)
+                            .find(interfaceProperty)
                             != theTarget->GetProperties().end();
     PropertyType ifacePropContent =
                     getTypedProperty<PropertyType>(theTarget,
-                              ("INTERFACE_" + p).c_str(), 0);
+                              interfaceProperty, 0);
 
     std::string reportEntry;
     if (ifaceIsSet)
@@ -5423,45 +5208,6 @@
 }
 
 //----------------------------------------------------------------------------
-bool isLinkDependentProperty(cmTarget const* tgt, const std::string &p,
-                             const std::string& interfaceProperty,
-                             const std::string& config)
-{
-  std::vector<cmTarget*> deps;
-  tgt->GetTransitiveTargetClosure(config, tgt, deps);
-
-  if(deps.empty())
-    {
-    return false;
-    }
-
-  for(std::vector<cmTarget*>::const_iterator li =
-      deps.begin();
-      li != deps.end(); ++li)
-    {
-    const char *prop = (*li)->GetProperty(interfaceProperty);
-    if (!prop)
-      {
-      continue;
-      }
-
-    std::vector<std::string> props;
-    cmSystemTools::ExpandListArgument(prop, props);
-
-    for(std::vector<std::string>::iterator pi = props.begin();
-        pi != props.end(); ++pi)
-      {
-      if (*pi == p)
-        {
-        return true;
-        }
-      }
-    }
-
-  return false;
-}
-
-//----------------------------------------------------------------------------
 bool cmTarget::IsLinkInterfaceDependentBoolProperty(const std::string &p,
                                            const std::string& config) const
 {
@@ -5470,9 +5216,7 @@
     {
     return false;
     }
-  return (p == "POSITION_INDEPENDENT_CODE") ||
-    isLinkDependentProperty(this, p, "COMPATIBLE_INTERFACE_BOOL",
-                                 config);
+  return this->GetCompatibleInterfaces(config).PropsBool.count(p) > 0;
 }
 
 //----------------------------------------------------------------------------
@@ -5484,9 +5228,7 @@
     {
     return false;
     }
-  return (p == "AUTOUIC_OPTIONS") ||
-    isLinkDependentProperty(this, p, "COMPATIBLE_INTERFACE_STRING",
-                                 config);
+  return this->GetCompatibleInterfaces(config).PropsString.count(p) > 0;
 }
 
 //----------------------------------------------------------------------------
@@ -5498,8 +5240,7 @@
     {
     return false;
     }
-  return isLinkDependentProperty(this, p, "COMPATIBLE_INTERFACE_NUMBER_MIN",
-                                 config);
+  return this->GetCompatibleInterfaces(config).PropsNumberMin.count(p) > 0;
 }
 
 //----------------------------------------------------------------------------
@@ -5511,8 +5252,7 @@
     {
     return false;
     }
-  return isLinkDependentProperty(this, p, "COMPATIBLE_INTERFACE_NUMBER_MAX",
-                                 config);
+  return this->GetCompatibleInterfaces(config).PropsNumberMax.count(p) > 0;
 }
 
 //----------------------------------------------------------------------------
@@ -5558,11 +5298,10 @@
 
 //----------------------------------------------------------------------------
 void cmTarget::GetLanguages(std::set<std::string>& languages,
-                            const std::string& config,
-                            cmTarget const* head) const
+                            const std::string& config) const
 {
   std::vector<cmSourceFile*> sourceFiles;
-  this->GetSourceFiles(sourceFiles, config, head);
+  this->GetSourceFiles(sourceFiles, config);
   for(std::vector<cmSourceFile*>::const_iterator
         i = sourceFiles.begin(); i != sourceFiles.end(); ++i)
     {
@@ -5598,7 +5337,7 @@
   for(std::vector<cmTarget*>::const_iterator
       i = objectLibraries.begin(); i != objectLibraries.end(); ++i)
     {
-    (*i)->GetLanguages(languages, config, head);
+    (*i)->GetLanguages(languages, config);
     }
 }
 
@@ -5646,7 +5385,7 @@
 #if defined(CMAKE_USE_ELF_PARSER)
   // Enable if the rpath flag uses a separator and the target uses ELF
   // binaries.
-  std::string ll = this->GetLinkerLanguage(config, this);
+  std::string ll = this->GetLinkerLanguage(config);
   if(!ll.empty())
     {
     std::string sepVar = "CMAKE_SHARED_LIBRARY_RUNTIME_";
@@ -5671,8 +5410,7 @@
 
 //----------------------------------------------------------------------------
 cmTarget::ImportInfo const*
-cmTarget::GetImportInfo(const std::string& config,
-                        cmTarget const* headTarget) const
+cmTarget::GetImportInfo(const std::string& config) const
 {
   // There is no imported information for non-imported targets.
   if(!this->IsImported())
@@ -5691,16 +5429,15 @@
     {
     config_upper = "NOCONFIG";
     }
-  TargetConfigPair key(headTarget, config_upper);
   typedef cmTargetInternals::ImportInfoMapType ImportInfoMapType;
 
   ImportInfoMapType::const_iterator i =
-    this->Internal->ImportInfoMap.find(key);
+    this->Internal->ImportInfoMap.find(config_upper);
   if(i == this->Internal->ImportInfoMap.end())
     {
     ImportInfo info;
-    this->ComputeImportInfo(config_upper, info, headTarget);
-    ImportInfoMapType::value_type entry(key, info);
+    this->ComputeImportInfo(config_upper, info);
+    ImportInfoMapType::value_type entry(config_upper, info);
     i = this->Internal->ImportInfoMap.insert(entry).first;
     }
 
@@ -5852,8 +5589,7 @@
 
 //----------------------------------------------------------------------------
 void cmTarget::ComputeImportInfo(std::string const& desired_config,
-                                 ImportInfo& info,
-                                 cmTarget const* headTarget) const
+                                 ImportInfo& info) const
 {
   // This method finds information about an imported target from its
   // properties.  The "IMPORTED_" namespace is reserved for properties
@@ -5892,19 +5628,8 @@
     }
   if(propertyLibs)
     {
-    cmGeneratorExpression ge;
-
-    cmGeneratorExpressionDAGChecker dagChecker(
-                                        this->GetName(),
-                                        linkProp, 0, 0);
-    cmSystemTools::ExpandListArgument(ge.Parse(propertyLibs)
-                                       ->Evaluate(this->Makefile,
-                                                  desired_config,
-                                                  false,
-                                                  headTarget,
-                                                  this,
-                                                  &dagChecker),
-                                    info.LinkInterface.Libraries);
+    info.LibrariesProp = linkProp;
+    info.Libraries = propertyLibs;
     }
   }
   if(this->GetType() == INTERFACE_LIBRARY)
@@ -5990,13 +5715,12 @@
   linkProp += suffix;
   if(const char* config_libs = this->GetProperty(linkProp))
     {
-    cmSystemTools::ExpandListArgument(config_libs,
-                                      info.LinkInterface.SharedDeps);
+    info.SharedDeps = config_libs;
     }
   else if(const char* libs =
           this->GetProperty("IMPORTED_LINK_DEPENDENT_LIBRARIES"))
     {
-    cmSystemTools::ExpandListArgument(libs, info.LinkInterface.SharedDeps);
+    info.SharedDeps = libs;
     }
   }
 
@@ -6007,14 +5731,12 @@
     linkProp += suffix;
     if(const char* config_libs = this->GetProperty(linkProp))
       {
-      cmSystemTools::ExpandListArgument(config_libs,
-                                        info.LinkInterface.Languages);
+      info.Languages = config_libs;
       }
     else if(const char* libs =
             this->GetProperty("IMPORTED_LINK_INTERFACE_LANGUAGES"))
       {
-      cmSystemTools::ExpandListArgument(libs,
-                                        info.LinkInterface.Languages);
+      info.Languages = libs;
       }
     }
 
@@ -6025,12 +5747,12 @@
     linkProp += suffix;
     if(const char* config_reps = this->GetProperty(linkProp))
       {
-      sscanf(config_reps, "%u", &info.LinkInterface.Multiplicity);
+      sscanf(config_reps, "%u", &info.Multiplicity);
       }
     else if(const char* reps =
             this->GetProperty("IMPORTED_LINK_INTERFACE_MULTIPLICITY"))
       {
-      sscanf(reps, "%u", &info.LinkInterface.Multiplicity);
+      sscanf(reps, "%u", &info.Multiplicity);
       }
     }
 }
@@ -6043,11 +5765,7 @@
   // Imported targets have their own link interface.
   if(this->IsImported())
     {
-    if(cmTarget::ImportInfo const* info = this->GetImportInfo(config, head))
-      {
-      return &info->LinkInterface;
-      }
-    return 0;
+    return this->GetImportLinkInterface(config, head, false);
     }
 
   // Link interfaces are not supported for executables that do not
@@ -6059,48 +5777,46 @@
     }
 
   // Lookup any existing link interface for this configuration.
-  TargetConfigPair key(head, cmSystemTools::UpperCase(config));
+  std::string CONFIG = cmSystemTools::UpperCase(config);
+  cmTargetInternals::HeadToLinkInterfaceMap& hm =
+    this->Internal->LinkInterfaceMap[CONFIG];
 
-  cmTargetInternals::LinkInterfaceMapType::iterator
-    i = this->Internal->LinkInterfaceMap.find(key);
-  if(i == this->Internal->LinkInterfaceMap.end())
+  // If the link interface does not depend on the head target
+  // then return the one we computed first.
+  if(!hm.empty() && !hm.begin()->second.HadHeadSensitiveCondition)
     {
-    // Compute the link interface for this configuration.
-    cmTargetInternals::OptionalLinkInterface iface;
-    iface.ExplicitLibraries =
-        this->ComputeLinkInterfaceLibraries(config, iface, head, iface.Exists);
-    if (iface.Exists)
+    return &hm.begin()->second;
+    }
+
+  cmTargetInternals::OptionalLinkInterface& iface = hm[head];
+  if(!iface.LibrariesDone)
+    {
+    iface.LibrariesDone = true;
+    this->Internal->ComputeLinkInterfaceLibraries(
+      this, config, iface, head, false);
+    }
+  if(!iface.AllDone)
+    {
+    iface.AllDone = true;
+    if(iface.Exists)
       {
-      this->Internal->ComputeLinkInterface(this, config, iface,
-                                           head, iface.ExplicitLibraries);
+      this->Internal->ComputeLinkInterface(this, config, iface, head);
       }
-
-    // Store the information for this configuration.
-    cmTargetInternals::LinkInterfaceMapType::value_type entry(key, iface);
-    i = this->Internal->LinkInterfaceMap.insert(entry).first;
-    }
-  else if(!i->second.Complete && i->second.Exists)
-    {
-    this->Internal->ComputeLinkInterface(this, config, i->second, head,
-                                         i->second.ExplicitLibraries);
     }
 
-  return i->second.Exists ? &i->second : 0;
+  return iface.Exists? &iface : 0;
 }
 
 //----------------------------------------------------------------------------
-cmTarget::LinkInterface const*
+cmTarget::LinkInterfaceLibraries const*
 cmTarget::GetLinkInterfaceLibraries(const std::string& config,
-                                    cmTarget const* head) const
+                                    cmTarget const* head,
+                                    bool usage_requirements_only) const
 {
   // Imported targets have their own link interface.
   if(this->IsImported())
     {
-    if(cmTarget::ImportInfo const* info = this->GetImportInfo(config, head))
-      {
-      return &info->LinkInterface;
-      }
-    return 0;
+    return this->GetImportLinkInterface(config, head, usage_requirements_only);
     }
 
   // Link interfaces are not supported for executables that do not
@@ -6112,136 +5828,162 @@
     }
 
   // Lookup any existing link interface for this configuration.
-  TargetConfigPair key(head, cmSystemTools::UpperCase(config));
+  std::string CONFIG = cmSystemTools::UpperCase(config);
+  cmTargetInternals::HeadToLinkInterfaceMap& hm =
+    (usage_requirements_only ?
+     this->Internal->LinkInterfaceUsageRequirementsOnlyMap[CONFIG] :
+     this->Internal->LinkInterfaceMap[CONFIG]);
 
-  cmTargetInternals::LinkInterfaceMapType::iterator
-    i = this->Internal->LinkInterfaceMap.find(key);
-  if(i == this->Internal->LinkInterfaceMap.end())
+  // If the link interface does not depend on the head target
+  // then return the one we computed first.
+  if(!hm.empty() && !hm.begin()->second.HadHeadSensitiveCondition)
     {
-    // Compute the link interface for this configuration.
-    cmTargetInternals::OptionalLinkInterface iface;
-    iface.ExplicitLibraries = this->ComputeLinkInterfaceLibraries(config,
-                                                                iface,
-                                                                head,
-                                                                iface.Exists);
-
-    // Store the information for this configuration.
-    cmTargetInternals::LinkInterfaceMapType::value_type entry(key, iface);
-    i = this->Internal->LinkInterfaceMap.insert(entry).first;
+    return &hm.begin()->second;
     }
 
-  return i->second.Exists ? &i->second : 0;
+  cmTargetInternals::OptionalLinkInterface& iface = hm[head];
+  if(!iface.LibrariesDone)
+    {
+    iface.LibrariesDone = true;
+    this->Internal->ComputeLinkInterfaceLibraries(
+      this, config, iface, head, usage_requirements_only);
+    }
+
+  return iface.Exists? &iface : 0;
+}
+
+//----------------------------------------------------------------------------
+cmTarget::LinkInterface const*
+cmTarget::GetImportLinkInterface(const std::string& config,
+                                 cmTarget const* headTarget,
+                                 bool usage_requirements_only) const
+{
+  cmTarget::ImportInfo const* info = this->GetImportInfo(config);
+  if(!info)
+    {
+    return 0;
+    }
+
+  std::string CONFIG = cmSystemTools::UpperCase(config);
+  cmTargetInternals::HeadToLinkInterfaceMap& hm =
+    (usage_requirements_only ?
+     this->Internal->LinkInterfaceUsageRequirementsOnlyMap[CONFIG] :
+     this->Internal->LinkInterfaceMap[CONFIG]);
+
+  // If the link interface does not depend on the head target
+  // then return the one we computed first.
+  if(!hm.empty() && !hm.begin()->second.HadHeadSensitiveCondition)
+    {
+    return &hm.begin()->second;
+    }
+
+  cmTargetInternals::OptionalLinkInterface& iface = hm[headTarget];
+  if(!iface.AllDone)
+    {
+    iface.AllDone = true;
+    iface.Multiplicity = info->Multiplicity;
+    cmSystemTools::ExpandListArgument(info->Languages, iface.Languages);
+    this->ExpandLinkItems(info->LibrariesProp, info->Libraries, config,
+                          headTarget, usage_requirements_only,
+                          iface.Libraries,
+                          iface.HadHeadSensitiveCondition);
+    std::vector<std::string> deps;
+    cmSystemTools::ExpandListArgument(info->SharedDeps, deps);
+    this->LookupLinkItems(deps, iface.SharedDeps);
+    }
+
+  return &iface;
 }
 
 //----------------------------------------------------------------------------
 void processILibs(const std::string& config,
                   cmTarget const* headTarget,
-                  std::string const& name,
-                  std::vector<cmTarget*>& tgts, std::set<cmTarget*>& emitted)
+                  cmLinkItem const& item,
+                  std::vector<cmTarget const*>& tgts,
+                  std::set<cmTarget const*>& emitted)
 {
-  if (cmTarget* tgt = headTarget->GetMakefile()
-                                ->FindTargetToUse(name))
+  if (item.Target && emitted.insert(item.Target).second)
     {
-    if (emitted.insert(tgt).second)
+    tgts.push_back(item.Target);
+    if(cmTarget::LinkInterfaceLibraries const* iface =
+       item.Target->GetLinkInterfaceLibraries(config, headTarget, true))
       {
-      tgts.push_back(tgt);
-      std::vector<std::string> ilibs;
-      cmTarget::LinkInterface const* iface =
-                          tgt->GetLinkInterfaceLibraries(config, headTarget);
-      if (iface)
-        {
-        for(std::vector<std::string>::const_iterator
+      for(std::vector<cmLinkItem>::const_iterator
             it = iface->Libraries.begin();
-            it != iface->Libraries.end(); ++it)
-          {
-          processILibs(config, headTarget, *it, tgts, emitted);
-          }
-        }
-      }
-    }
-}
-
-//----------------------------------------------------------------------------
-void cmTarget::GetTransitiveTargetClosure(const std::string& config,
-                                      cmTarget const* headTarget,
-                                      std::vector<cmTarget*> &tgts) const
-{
-  std::set<cmTarget*> emitted;
-
-  cmTarget::LinkImplementation const* impl
-      = this->GetLinkImplementationLibraries(config, headTarget);
-
-  for(std::vector<std::string>::const_iterator it = impl->Libraries.begin();
-      it != impl->Libraries.end(); ++it)
-    {
-      processILibs(config, headTarget, *it, tgts, emitted);
-    }
-}
-
-//----------------------------------------------------------------------------
-void cmTarget::GetTransitivePropertyTargets(const std::string& config,
-                                      cmTarget const* headTarget,
-                                      std::vector<cmTarget*> &tgts) const
-{
-  cmTarget::LinkInterface const* iface
-                        = this->GetLinkInterfaceLibraries(config, headTarget);
-  if (!iface)
-    {
-    return;
-    }
-  if(this->GetType() != STATIC_LIBRARY
-      || this->GetPolicyStatusCMP0022() == cmPolicies::WARN
-      || this->GetPolicyStatusCMP0022() == cmPolicies::OLD)
-    {
-    for(std::vector<std::string>::const_iterator it = iface->Libraries.begin();
-        it != iface->Libraries.end(); ++it)
-      {
-      if (cmTarget* tgt = headTarget->GetMakefile()
-                                    ->FindTargetToUse(*it))
+          it != iface->Libraries.end(); ++it)
         {
-        tgts.push_back(tgt);
+        processILibs(config, headTarget, *it, tgts, emitted);
         }
       }
-    return;
-    }
-
-  const char* linkIfaceProp = "INTERFACE_LINK_LIBRARIES";
-  const char* interfaceLibs = this->GetProperty(linkIfaceProp);
-
-  if (!interfaceLibs)
-    {
-    return;
-    }
-
-  // The interface libraries have been explicitly set.
-  cmGeneratorExpression ge;
-  cmGeneratorExpressionDAGChecker dagChecker(this->GetName(),
-                                             linkIfaceProp, 0, 0);
-  dagChecker.SetTransitivePropertiesOnly();
-  std::vector<std::string> libs;
-  cmSystemTools::ExpandListArgument(ge.Parse(interfaceLibs)->Evaluate(
-                                      this->Makefile,
-                                      config,
-                                      false,
-                                      headTarget,
-                                      this, &dagChecker), libs);
-
-  for(std::vector<std::string>::const_iterator it = libs.begin();
-      it != libs.end(); ++it)
-    {
-    if (cmTarget* tgt = headTarget->GetMakefile()
-                                  ->FindTargetToUse(*it))
-      {
-      tgts.push_back(tgt);
-      }
     }
 }
 
 //----------------------------------------------------------------------------
-const char* cmTarget::ComputeLinkInterfaceLibraries(const std::string& config,
-                                           LinkInterface& iface,
-                                           cmTarget const* headTarget,
-                                           bool &exists) const
+std::vector<cmTarget const*> const&
+cmTarget::GetLinkImplementationClosure(const std::string& config) const
+{
+  cmTargetInternals::LinkImplClosure& tgts =
+    this->Internal->LinkImplClosureMap[config];
+  if(!tgts.Done)
+    {
+    tgts.Done = true;
+    std::set<cmTarget const*> emitted;
+
+    cmTarget::LinkImplementationLibraries const* impl
+      = this->GetLinkImplementationLibraries(config);
+
+    for(std::vector<cmLinkImplItem>::const_iterator
+          it = impl->Libraries.begin();
+        it != impl->Libraries.end(); ++it)
+      {
+      processILibs(config, this, *it, tgts , emitted);
+      }
+    }
+  return tgts;
+}
+
+//----------------------------------------------------------------------------
+cmTarget::CompatibleInterfaces const&
+cmTarget::GetCompatibleInterfaces(std::string const& config) const
+{
+  cmTargetInternals::CompatibleInterfaces& compat =
+    this->Internal->CompatibleInterfacesMap[config];
+  if(!compat.Done)
+    {
+    compat.Done = true;
+    compat.PropsBool.insert("POSITION_INDEPENDENT_CODE");
+    compat.PropsString.insert("AUTOUIC_OPTIONS");
+    std::vector<cmTarget const*> const& deps =
+      this->GetLinkImplementationClosure(config);
+    for(std::vector<cmTarget const*>::const_iterator li = deps.begin();
+        li != deps.end(); ++li)
+      {
+#define CM_READ_COMPATIBLE_INTERFACE(X, x) \
+      if(const char* prop = (*li)->GetProperty("COMPATIBLE_INTERFACE_" #X)) \
+        { \
+        std::vector<std::string> props; \
+        cmSystemTools::ExpandListArgument(prop, props); \
+        std::copy(props.begin(), props.end(), \
+                  std::inserter(compat.Props##x, compat.Props##x.begin())); \
+        }
+      CM_READ_COMPATIBLE_INTERFACE(BOOL, Bool)
+      CM_READ_COMPATIBLE_INTERFACE(STRING, String)
+      CM_READ_COMPATIBLE_INTERFACE(NUMBER_MIN, NumberMin)
+      CM_READ_COMPATIBLE_INTERFACE(NUMBER_MAX, NumberMax)
+#undef CM_READ_COMPATIBLE_INTERFACE
+      }
+    }
+  return compat;
+}
+
+//----------------------------------------------------------------------------
+void
+cmTargetInternals::ComputeLinkInterfaceLibraries(
+  cmTarget const* thisTarget,
+  const std::string& config,
+  OptionalLinkInterface& iface,
+  cmTarget const* headTarget,
+  bool usage_requirements_only)
 {
   // Construct the property name suffix for this configuration.
   std::string suffix = "_";
@@ -6258,15 +6000,15 @@
   // libraries and executables that export symbols.
   const char* explicitLibraries = 0;
   std::string linkIfaceProp;
-  if(this->PolicyStatusCMP0022 != cmPolicies::OLD &&
-     this->PolicyStatusCMP0022 != cmPolicies::WARN)
+  if(thisTarget->PolicyStatusCMP0022 != cmPolicies::OLD &&
+     thisTarget->PolicyStatusCMP0022 != cmPolicies::WARN)
     {
     // CMP0022 NEW behavior is to use INTERFACE_LINK_LIBRARIES.
     linkIfaceProp = "INTERFACE_LINK_LIBRARIES";
-    explicitLibraries = this->GetProperty(linkIfaceProp);
+    explicitLibraries = thisTarget->GetProperty(linkIfaceProp);
     }
-  else if(this->GetType() == cmTarget::SHARED_LIBRARY ||
-          this->IsExecutableWithExports())
+  else if(thisTarget->GetType() == cmTarget::SHARED_LIBRARY ||
+          thisTarget->IsExecutableWithExports())
     {
     // CMP0022 OLD behavior is to use LINK_INTERFACE_LIBRARIES if set on a
     // shared lib or executable.
@@ -6274,31 +6016,32 @@
     // Lookup the per-configuration property.
     linkIfaceProp = "LINK_INTERFACE_LIBRARIES";
     linkIfaceProp += suffix;
-    explicitLibraries = this->GetProperty(linkIfaceProp);
+    explicitLibraries = thisTarget->GetProperty(linkIfaceProp);
 
     // If not set, try the generic property.
     if(!explicitLibraries)
       {
       linkIfaceProp = "LINK_INTERFACE_LIBRARIES";
-      explicitLibraries = this->GetProperty(linkIfaceProp);
+      explicitLibraries = thisTarget->GetProperty(linkIfaceProp);
       }
     }
 
-  if(explicitLibraries && this->PolicyStatusCMP0022 == cmPolicies::WARN &&
-     !this->Internal->PolicyWarnedCMP0022)
+  if(explicitLibraries &&
+     thisTarget->PolicyStatusCMP0022 == cmPolicies::WARN &&
+     !this->PolicyWarnedCMP0022)
     {
     // Compare the explicitly set old link interface properties to the
     // preferred new link interface property one and warn if different.
     const char* newExplicitLibraries =
-      this->GetProperty("INTERFACE_LINK_LIBRARIES");
+      thisTarget->GetProperty("INTERFACE_LINK_LIBRARIES");
     if (newExplicitLibraries
         && strcmp(newExplicitLibraries, explicitLibraries) != 0)
       {
       cmOStringStream w;
       w <<
-        (this->Makefile->GetPolicies()
+        (thisTarget->Makefile->GetPolicies()
          ->GetPolicyWarning(cmPolicies::CMP0022)) << "\n"
-        "Target \"" << this->GetName() << "\" has an "
+        "Target \"" << thisTarget->GetName() << "\" has an "
         "INTERFACE_LINK_LIBRARIES property which differs from its " <<
         linkIfaceProp << " properties."
         "\n"
@@ -6306,70 +6049,62 @@
         "  " << newExplicitLibraries << "\n" <<
         linkIfaceProp << ":\n"
         "  " << (explicitLibraries ? explicitLibraries : "(empty)") << "\n";
-      this->Makefile->IssueMessage(cmake::AUTHOR_WARNING, w.str());
-      this->Internal->PolicyWarnedCMP0022 = true;
+      thisTarget->Makefile->IssueMessage(cmake::AUTHOR_WARNING, w.str());
+      this->PolicyWarnedCMP0022 = true;
       }
     }
 
   // There is no implicit link interface for executables or modules
   // so if none was explicitly set then there is no link interface.
   if(!explicitLibraries &&
-     (this->GetType() == cmTarget::EXECUTABLE ||
-      (this->GetType() == cmTarget::MODULE_LIBRARY)))
+     (thisTarget->GetType() == cmTarget::EXECUTABLE ||
+      (thisTarget->GetType() == cmTarget::MODULE_LIBRARY)))
     {
-    exists = false;
-    return 0;
+    return;
     }
-  exists = true;
+  iface.Exists = true;
+  iface.ExplicitLibraries = explicitLibraries;
 
   if(explicitLibraries)
     {
     // The interface libraries have been explicitly set.
-    cmGeneratorExpression ge;
-    cmGeneratorExpressionDAGChecker dagChecker(this->GetName(),
-                                               linkIfaceProp, 0, 0);
-    cmSystemTools::ExpandListArgument(ge.Parse(explicitLibraries)->Evaluate(
-                                        this->Makefile,
-                                        config,
-                                        false,
-                                        headTarget,
-                                        this, &dagChecker), iface.Libraries);
+    thisTarget->ExpandLinkItems(linkIfaceProp, explicitLibraries, config,
+                                headTarget, usage_requirements_only,
+                                iface.Libraries,
+                                iface.HadHeadSensitiveCondition);
     }
-  else if (this->PolicyStatusCMP0022 == cmPolicies::WARN
-        || this->PolicyStatusCMP0022 == cmPolicies::OLD)
+  else if (thisTarget->PolicyStatusCMP0022 == cmPolicies::WARN
+        || thisTarget->PolicyStatusCMP0022 == cmPolicies::OLD)
     // If CMP0022 is NEW then the plain tll signature sets the
     // INTERFACE_LINK_LIBRARIES, so if we get here then the project
     // cleared the property explicitly and we should not fall back
     // to the link implementation.
     {
     // The link implementation is the default link interface.
-    LinkImplementation const* impl =
-        this->GetLinkImplementationLibraries(config, headTarget);
-    iface.Libraries = impl->Libraries;
-    if(this->PolicyStatusCMP0022 == cmPolicies::WARN &&
-       !this->Internal->PolicyWarnedCMP0022)
+    cmTarget::LinkImplementationLibraries const* impl =
+      thisTarget->GetLinkImplementationLibrariesInternal(config, headTarget);
+    std::copy(impl->Libraries.begin(), impl->Libraries.end(),
+              std::back_inserter(iface.Libraries));
+    if(thisTarget->PolicyStatusCMP0022 == cmPolicies::WARN &&
+       !this->PolicyWarnedCMP0022 && !usage_requirements_only)
       {
       // Compare the link implementation fallback link interface to the
       // preferred new link interface property and warn if different.
-      cmGeneratorExpression ge;
-      cmGeneratorExpressionDAGChecker dagChecker(this->GetName(),
-                                      "INTERFACE_LINK_LIBRARIES", 0, 0);
-      std::vector<std::string> ifaceLibs;
-      const char* newExplicitLibraries =
-        this->GetProperty("INTERFACE_LINK_LIBRARIES");
-      cmSystemTools::ExpandListArgument(
-        ge.Parse(newExplicitLibraries)->Evaluate(this->Makefile,
-                                                 config,
-                                                 false,
-                                                 headTarget,
-                                                 this, &dagChecker),
-        ifaceLibs);
-      if (ifaceLibs != impl->Libraries)
+      std::vector<cmLinkItem> ifaceLibs;
+      static const std::string newProp = "INTERFACE_LINK_LIBRARIES";
+      if(const char* newExplicitLibraries = thisTarget->GetProperty(newProp))
+        {
+        bool hadHeadSensitiveConditionDummy = false;
+        thisTarget->ExpandLinkItems(newProp, newExplicitLibraries, config,
+                                    headTarget, usage_requirements_only,
+                                ifaceLibs, hadHeadSensitiveConditionDummy);
+        }
+      if (ifaceLibs != iface.Libraries)
         {
         std::string oldLibraries;
         std::string newLibraries;
         const char *sep = "";
-        for(std::vector<std::string>::const_iterator it
+        for(std::vector<cmLinkImplItem>::const_iterator it
               = impl->Libraries.begin(); it != impl->Libraries.end(); ++it)
           {
           oldLibraries += sep;
@@ -6377,7 +6112,7 @@
           sep = ";";
           }
         sep = "";
-        for(std::vector<std::string>::const_iterator it
+        for(std::vector<cmLinkItem>::const_iterator it
               = ifaceLibs.begin(); it != ifaceLibs.end(); ++it)
           {
           newLibraries += sep;
@@ -6391,9 +6126,9 @@
 
         cmOStringStream w;
         w <<
-          (this->Makefile->GetPolicies()
+          (thisTarget->Makefile->GetPolicies()
            ->GetPolicyWarning(cmPolicies::CMP0022)) << "\n"
-          "Target \"" << this->GetName() << "\" has an "
+          "Target \"" << thisTarget->GetName() << "\" has an "
           "INTERFACE_LINK_LIBRARIES property.  "
           "This should be preferred as the source of the link interface "
           "for this library but because CMP0022 is not set CMake is "
@@ -6404,22 +6139,20 @@
           "  " << newLibraries << "\n"
           "Link implementation:\n"
           "  " << oldLibraries << "\n";
-        this->Makefile->IssueMessage(cmake::AUTHOR_WARNING, w.str());
-        this->Internal->PolicyWarnedCMP0022 = true;
+        thisTarget->Makefile->IssueMessage(cmake::AUTHOR_WARNING, w.str());
+        this->PolicyWarnedCMP0022 = true;
         }
       }
     }
-  return explicitLibraries;
 }
 
 //----------------------------------------------------------------------------
 void cmTargetInternals::ComputeLinkInterface(cmTarget const* thisTarget,
                                              const std::string& config,
                                              OptionalLinkInterface& iface,
-                                             cmTarget const* headTarget,
-                                          const char* explicitLibraries) const
+                                             cmTarget const* headTarget) const
 {
-  if(explicitLibraries)
+  if(iface.ExplicitLibraries)
     {
     if(thisTarget->GetType() == cmTarget::SHARED_LIBRARY
         || thisTarget->GetType() == cmTarget::STATIC_LIBRARY
@@ -6427,8 +6160,8 @@
       {
       // Shared libraries may have runtime implementation dependencies
       // on other shared libraries that are not in the interface.
-      std::set<std::string> emitted;
-      for(std::vector<std::string>::const_iterator
+      UNORDERED_SET<std::string> emitted;
+      for(std::vector<cmLinkItem>::const_iterator
           li = iface.Libraries.begin(); li != iface.Libraries.end(); ++li)
         {
         emitted.insert(*li);
@@ -6436,16 +6169,16 @@
       if (thisTarget->GetType() != cmTarget::INTERFACE_LIBRARY)
         {
         cmTarget::LinkImplementation const* impl =
-            thisTarget->GetLinkImplementation(config, headTarget);
-        for(std::vector<std::string>::const_iterator
+            thisTarget->GetLinkImplementation(config);
+        for(std::vector<cmLinkImplItem>::const_iterator
               li = impl->Libraries.begin(); li != impl->Libraries.end(); ++li)
           {
           if(emitted.insert(*li).second)
             {
-            if(cmTarget* tgt = thisTarget->Makefile->FindTargetToUse(*li))
+            if(li->Target)
               {
               // This is a runtime dependency on another shared library.
-              if(tgt->GetType() == cmTarget::SHARED_LIBRARY)
+              if(li->Target->GetType() == cmTarget::SHARED_LIBRARY)
                 {
                 iface.SharedDeps.push_back(*li);
                 }
@@ -6466,8 +6199,9 @@
         || thisTarget->PolicyStatusCMP0022 == cmPolicies::OLD)
     {
     // The link implementation is the default link interface.
-    cmTarget::LinkImplementation const*
-                impl = thisTarget->GetLinkImplementation(config, headTarget);
+    cmTarget::LinkImplementationLibraries const*
+      impl = thisTarget->GetLinkImplementationLibrariesInternal(config,
+                                                                headTarget);
     iface.ImplementationIsInterface = true;
     iface.WrongConfigLibraries = impl->WrongConfigLibraries;
     }
@@ -6476,7 +6210,7 @@
     {
     // Targets using this archive need its language runtime libraries.
     if(cmTarget::LinkImplementation const* impl =
-       thisTarget->GetLinkImplementation(config, headTarget))
+       thisTarget->GetLinkImplementation(config))
       {
       iface.Languages = impl->Languages;
       }
@@ -6509,13 +6243,37 @@
       sscanf(reps, "%u", &iface.Multiplicity);
       }
     }
-  iface.Complete = true;
+}
+
+//----------------------------------------------------------------------------
+void cmTargetInternals::AddInterfaceEntries(
+  cmTarget const* thisTarget, std::string const& config,
+  std::string const& prop, std::vector<TargetPropertyEntry*>& entries)
+{
+  if(cmTarget::LinkImplementationLibraries const* impl =
+     thisTarget->GetLinkImplementationLibraries(config))
+    {
+    for (std::vector<cmLinkImplItem>::const_iterator
+           it = impl->Libraries.begin(), end = impl->Libraries.end();
+         it != end; ++it)
+      {
+      if(it->Target)
+        {
+        std::string genex =
+          "$<TARGET_PROPERTY:" + *it + "," + prop + ">";
+        cmGeneratorExpression ge(&it->Backtrace);
+        cmsys::auto_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(genex);
+        cge->SetEvaluateForBuildsystem(true);
+        entries.push_back(
+          new cmTargetInternals::TargetPropertyEntry(cge, *it));
+        }
+      }
+    }
 }
 
 //----------------------------------------------------------------------------
 cmTarget::LinkImplementation const*
-cmTarget::GetLinkImplementation(const std::string& config,
-                                cmTarget const* head) const
+cmTarget::GetLinkImplementation(const std::string& config) const
 {
   // There is no link implementation for imported targets.
   if(this->IsImported())
@@ -6523,34 +6281,35 @@
     return 0;
     }
 
-  // Lookup any existing link implementation for this configuration.
-  TargetConfigPair key(head, cmSystemTools::UpperCase(config));
-
-  cmTargetInternals::LinkImplMapType::iterator
-    i = this->Internal->LinkImplMap.find(key);
-  if(i == this->Internal->LinkImplMap.end())
+  // Populate the link implementation for this configuration.
+  std::string CONFIG = cmSystemTools::UpperCase(config);
+  cmTargetInternals::OptionalLinkImplementation&
+    impl = this->Internal->LinkImplMap[CONFIG][this];
+  if(!impl.LibrariesDone)
     {
-    // Compute the link implementation for this configuration.
-    LinkImplementation impl;
-    this->ComputeLinkImplementation(config, impl, head);
-    this->ComputeLinkImplementationLanguages(config, impl, head);
-
-    // Store the information for this configuration.
-    cmTargetInternals::LinkImplMapType::value_type entry(key, impl);
-    i = this->Internal->LinkImplMap.insert(entry).first;
+    impl.LibrariesDone = true;
+    this->Internal
+      ->ComputeLinkImplementationLibraries(this, config, impl, this);
     }
-  else if (i->second.Languages.empty())
+  if(!impl.LanguagesDone)
     {
-    this->ComputeLinkImplementationLanguages(config, i->second, head);
+    impl.LanguagesDone = true;
+    this->Internal->ComputeLinkImplementationLanguages(this, config, impl);
     }
-
-  return &i->second;
+  return &impl;
 }
 
 //----------------------------------------------------------------------------
-cmTarget::LinkImplementation const*
-cmTarget::GetLinkImplementationLibraries(const std::string& config,
-                                         cmTarget const* head) const
+cmTarget::LinkImplementationLibraries const*
+cmTarget::GetLinkImplementationLibraries(const std::string& config) const
+{
+  return this->GetLinkImplementationLibrariesInternal(config, this);
+}
+
+//----------------------------------------------------------------------------
+cmTarget::LinkImplementationLibraries const*
+cmTarget::GetLinkImplementationLibrariesInternal(const std::string& config,
+                                                 cmTarget const* head) const
 {
   // There is no link implementation for imported targets.
   if(this->IsImported())
@@ -6558,110 +6317,150 @@
     return 0;
     }
 
-  // Lookup any existing link implementation for this configuration.
-  TargetConfigPair key(head, cmSystemTools::UpperCase(config));
+  // Populate the link implementation libraries for this configuration.
+  std::string CONFIG = cmSystemTools::UpperCase(config);
+  cmTargetInternals::HeadToLinkImplementationMap& hm =
+    this->Internal->LinkImplMap[CONFIG];
 
-  cmTargetInternals::LinkImplMapType::iterator
-    i = this->Internal->LinkImplMap.find(key);
-  if(i == this->Internal->LinkImplMap.end())
+  // If the link implementation does not depend on the head target
+  // then return the one we computed first.
+  if(!hm.empty() && !hm.begin()->second.HadHeadSensitiveCondition)
     {
-    // Compute the link implementation for this configuration.
-    LinkImplementation impl;
-    this->ComputeLinkImplementation(config, impl, head);
-
-    // Store the information for this configuration.
-    cmTargetInternals::LinkImplMapType::value_type entry(key, impl);
-    i = this->Internal->LinkImplMap.insert(entry).first;
+    return &hm.begin()->second;
     }
 
-  return &i->second;
+  cmTargetInternals::OptionalLinkImplementation& impl = hm[head];
+  if(!impl.LibrariesDone)
+    {
+    impl.LibrariesDone = true;
+    this->Internal
+      ->ComputeLinkImplementationLibraries(this, config, impl, head);
+    }
+  return &impl;
 }
 
 //----------------------------------------------------------------------------
-void cmTarget::ComputeLinkImplementation(const std::string& config,
-                                         LinkImplementation& impl,
-                                         cmTarget const* head) const
+void
+cmTargetInternals::ComputeLinkImplementationLibraries(
+  cmTarget const* thisTarget,
+  const std::string& config,
+  OptionalLinkImplementation& impl,
+  cmTarget const* head) const
 {
   // Collect libraries directly linked in this configuration.
-  std::vector<std::string> llibs;
-  this->GetDirectLinkLibraries(config, llibs, head);
-  for(std::vector<std::string>::const_iterator li = llibs.begin();
-      li != llibs.end(); ++li)
+  for (std::vector<cmValueWithOrigin>::const_iterator
+      le = this->LinkImplementationPropertyEntries.begin(),
+      end = this->LinkImplementationPropertyEntries.end();
+      le != end; ++le)
     {
-    // Skip entries that resolve to the target itself or are empty.
-    std::string item = this->CheckCMP0004(*li);
-    if(item == this->GetName() || item.empty())
+    std::vector<std::string> llibs;
+    cmGeneratorExpressionDAGChecker dagChecker(
+                                        thisTarget->GetName(),
+                                        "LINK_LIBRARIES", 0, 0);
+    cmGeneratorExpression ge(&le->Backtrace);
+    cmsys::auto_ptr<cmCompiledGeneratorExpression> const cge =
+      ge.Parse(le->Value);
+    std::string const evaluated =
+      cge->Evaluate(thisTarget->Makefile, config, false, head, &dagChecker);
+    cmSystemTools::ExpandListArgument(evaluated, llibs);
+    if(cge->GetHadHeadSensitiveCondition())
       {
-      if(item == this->GetName())
-        {
-        bool noMessage = false;
-        cmake::MessageType messageType = cmake::FATAL_ERROR;
-        cmOStringStream e;
-        switch(this->GetPolicyStatusCMP0038())
-          {
-          case cmPolicies::WARN:
-            {
-            e << (this->Makefile->GetPolicies()
-                  ->GetPolicyWarning(cmPolicies::CMP0038)) << "\n";
-            messageType = cmake::AUTHOR_WARNING;
-            }
-            break;
-          case cmPolicies::OLD:
-            noMessage = true;
-          case cmPolicies::REQUIRED_IF_USED:
-          case cmPolicies::REQUIRED_ALWAYS:
-          case cmPolicies::NEW:
-            // Issue the fatal message.
-            break;
-          }
-
-        if(!noMessage)
-          {
-          e << "Target \"" << this->GetName() << "\" links to itself.";
-          this->Makefile->GetCMakeInstance()->IssueMessage(messageType,
-                                                        e.str(),
-                                                        this->GetBacktrace());
-          if (messageType == cmake::FATAL_ERROR)
-            {
-            return;
-            }
-          }
-        }
-      continue;
+      impl.HadHeadSensitiveCondition = true;
       }
 
-    // The entry is meant for this configuration.
-    impl.Libraries.push_back(item);
+    for(std::vector<std::string>::const_iterator li = llibs.begin();
+        li != llibs.end(); ++li)
+      {
+      // Skip entries that resolve to the target itself or are empty.
+      std::string name = thisTarget->CheckCMP0004(*li);
+      if(name == thisTarget->GetName() || name.empty())
+        {
+        if(name == thisTarget->GetName())
+          {
+          bool noMessage = false;
+          cmake::MessageType messageType = cmake::FATAL_ERROR;
+          cmOStringStream e;
+          switch(thisTarget->GetPolicyStatusCMP0038())
+            {
+            case cmPolicies::WARN:
+              {
+              e << (thisTarget->Makefile->GetPolicies()
+                    ->GetPolicyWarning(cmPolicies::CMP0038)) << "\n";
+              messageType = cmake::AUTHOR_WARNING;
+              }
+              break;
+            case cmPolicies::OLD:
+              noMessage = true;
+            case cmPolicies::REQUIRED_IF_USED:
+            case cmPolicies::REQUIRED_ALWAYS:
+            case cmPolicies::NEW:
+              // Issue the fatal message.
+              break;
+            }
+
+          if(!noMessage)
+            {
+            e << "Target \"" << thisTarget->GetName() << "\" links to itself.";
+            thisTarget->Makefile->GetCMakeInstance()->IssueMessage(
+              messageType, e.str(), thisTarget->GetBacktrace());
+            if (messageType == cmake::FATAL_ERROR)
+              {
+              return;
+              }
+            }
+          }
+        continue;
+        }
+
+      // The entry is meant for this configuration.
+      impl.Libraries.push_back(
+        cmLinkImplItem(name, thisTarget->FindTargetToLink(name),
+                       le->Backtrace, evaluated != le->Value));
+      }
+
+    std::set<std::string> const& seenProps = cge->GetSeenTargetProperties();
+    for (std::set<std::string>::const_iterator it = seenProps.begin();
+        it != seenProps.end(); ++it)
+      {
+      if (!thisTarget->GetProperty(*it))
+        {
+        thisTarget->LinkImplicitNullProperties.insert(*it);
+        }
+      }
+    cge->GetMaxLanguageStandard(thisTarget, thisTarget->MaxLanguageStandards);
     }
 
-  cmTarget::LinkLibraryType linkType = this->ComputeLinkType(config);
-  LinkLibraryVectorType const& oldllibs = this->GetOriginalLinkLibraries();
+  cmTarget::LinkLibraryType linkType = thisTarget->ComputeLinkType(config);
+  cmTarget::LinkLibraryVectorType const& oldllibs =
+    thisTarget->GetOriginalLinkLibraries();
   for(cmTarget::LinkLibraryVectorType::const_iterator li = oldllibs.begin();
       li != oldllibs.end(); ++li)
     {
     if(li->second != cmTarget::GENERAL && li->second != linkType)
       {
-      std::string item = this->CheckCMP0004(li->first);
-      if(item == this->GetName() || item.empty())
+      std::string name = thisTarget->CheckCMP0004(li->first);
+      if(name == thisTarget->GetName() || name.empty())
         {
         continue;
         }
       // Support OLD behavior for CMP0003.
-      impl.WrongConfigLibraries.push_back(item);
+      impl.WrongConfigLibraries.push_back(
+        cmLinkItem(name, thisTarget->FindTargetToLink(name)));
       }
     }
 }
 
 //----------------------------------------------------------------------------
 void
-cmTarget::ComputeLinkImplementationLanguages(const std::string& config,
-                                             LinkImplementation& impl,
-                                             cmTarget const* head) const
+cmTargetInternals::ComputeLinkImplementationLanguages(
+  cmTarget const* thisTarget,
+  const std::string& config,
+  OptionalLinkImplementation& impl) const
 {
   // This target needs runtime libraries for its source languages.
   std::set<std::string> languages;
   // Get languages used in our source files.
-  this->GetLanguages(languages, config, head);
+  thisTarget->GetLanguages(languages, config);
   // Copy the set of langauges to the link implementation.
   for(std::set<std::string>::iterator li = languages.begin();
       li != languages.end(); ++li)
@@ -6671,6 +6470,37 @@
 }
 
 //----------------------------------------------------------------------------
+cmTarget const* cmTarget::FindTargetToLink(std::string const& name) const
+{
+  cmTarget const* tgt = this->Makefile->FindTargetToUse(name);
+
+  // Skip targets that will not really be linked.  This is probably a
+  // name conflict between an external library and an executable
+  // within the project.
+  if(tgt && tgt->GetType() == cmTarget::EXECUTABLE &&
+     !tgt->IsExecutableWithExports())
+    {
+    tgt = 0;
+    }
+
+  if(tgt && tgt->GetType() == cmTarget::OBJECT_LIBRARY)
+    {
+    cmOStringStream e;
+    e << "Target \"" << this->GetName() << "\" links to "
+      "OBJECT library \"" << tgt->GetName() << "\" but this is not "
+      "allowed.  "
+      "One may link only to STATIC or SHARED libraries, or to executables "
+      "with the ENABLE_EXPORTS property set.";
+    cmake* cm = this->Makefile->GetCMakeInstance();
+    cm->IssueMessage(cmake::FATAL_ERROR, e.str(), this->GetBacktrace());
+    tgt = 0;
+    }
+
+  // Return the target found, if any.
+  return tgt;
+}
+
+//----------------------------------------------------------------------------
 std::string cmTarget::CheckCMP0004(std::string const& item) const
 {
   // Strip whitespace off the library names because we used to do this
@@ -6868,9 +6698,13 @@
   const cmComputeLinkInformation::ItemVector &deps = info->GetItems();
 
   std::set<std::string> emittedBools;
+  static std::string strBool = "COMPATIBLE_INTERFACE_BOOL";
   std::set<std::string> emittedStrings;
+  static std::string strString = "COMPATIBLE_INTERFACE_STRING";
   std::set<std::string> emittedMinNumbers;
+  static std::string strNumMin = "COMPATIBLE_INTERFACE_NUMBER_MIN";
   std::set<std::string> emittedMaxNumbers;
+  static std::string strNumMax = "COMPATIBLE_INTERFACE_NUMBER_MAX";
 
   for(cmComputeLinkInformation::ItemVector::const_iterator li =
       deps.begin();
@@ -6882,14 +6716,14 @@
       }
 
     checkPropertyConsistency<bool>(this, li->Target,
-                                std::string("COMPATIBLE_INTERFACE_BOOL"),
+                                strBool,
                                 emittedBools, config, BoolType, 0);
     if (cmSystemTools::GetErrorOccuredFlag())
       {
       return;
       }
     checkPropertyConsistency<const char *>(this, li->Target,
-                                std::string("COMPATIBLE_INTERFACE_STRING"),
+                                strString,
                                 emittedStrings, config,
                                 StringType, 0);
     if (cmSystemTools::GetErrorOccuredFlag())
@@ -6897,7 +6731,7 @@
       return;
       }
     checkPropertyConsistency<const char *>(this, li->Target,
-                                std::string("COMPATIBLE_INTERFACE_NUMBER_MIN"),
+                                strNumMin,
                                 emittedMinNumbers, config,
                                 NumberMinType, 0);
     if (cmSystemTools::GetErrorOccuredFlag())
@@ -6905,7 +6739,7 @@
       return;
       }
     checkPropertyConsistency<const char *>(this, li->Target,
-                                std::string("COMPATIBLE_INTERFACE_NUMBER_MAX"),
+                                strNumMax,
                                 emittedMaxNumbers, config,
                                 NumberMaxType, 0);
     if (cmSystemTools::GetErrorOccuredFlag())
@@ -6921,26 +6755,27 @@
 
   if (!prop.empty())
     {
+    // Use a std::set to keep the error message sorted.
     std::set<std::string> props;
     std::set<std::string>::const_iterator i = emittedBools.find(prop);
     if (i != emittedBools.end())
       {
-      props.insert("COMPATIBLE_INTERFACE_BOOL");
+      props.insert(strBool);
       }
     i = emittedStrings.find(prop);
     if (i != emittedStrings.end())
       {
-      props.insert("COMPATIBLE_INTERFACE_STRING");
+      props.insert(strString);
       }
     i = emittedMinNumbers.find(prop);
     if (i != emittedMinNumbers.end())
       {
-      props.insert("COMPATIBLE_INTERFACE_NUMBER_MIN");
+      props.insert(strNumMin);
       }
     i = emittedMaxNumbers.find(prop);
     if (i != emittedMaxNumbers.end())
       {
-      props.insert("COMPATIBLE_INTERFACE_NUMBER_MAX");
+      props.insert(strNumMax);
       }
 
     std::string propsString = *props.begin();
@@ -6967,19 +6802,17 @@
 
 //----------------------------------------------------------------------------
 cmComputeLinkInformation*
-cmTarget::GetLinkInformation(const std::string& config,
-                             cmTarget const* head) const
+cmTarget::GetLinkInformation(const std::string& config) const
 {
-  cmTarget const* headTarget = head ? head : this;
   // Lookup any existing information for this configuration.
-  TargetConfigPair key(headTarget, cmSystemTools::UpperCase(config));
+  std::string key(cmSystemTools::UpperCase(config));
   cmTargetLinkInformationMap::iterator
     i = this->LinkInformation.find(key);
   if(i == this->LinkInformation.end())
     {
     // Compute information for this configuration.
     cmComputeLinkInformation* info =
-      new cmComputeLinkInformation(this, config, headTarget);
+      new cmComputeLinkInformation(this, config);
     if(!info || !info->Compute())
       {
       delete info;
diff --git a/Source/cmTarget.h b/Source/cmTarget.h
index 2d51835..a3ecca0 100644
--- a/Source/cmTarget.h
+++ b/Source/cmTarget.h
@@ -18,6 +18,9 @@
 #include "cmListFileCache.h"
 
 #include <cmsys/auto_ptr.hxx>
+#if defined(CMAKE_BUILD_WITH_CMAKE)
+#include <cmsys/hash_map.hxx>
+#endif
 
 #define CM_FOR_EACH_TARGET_POLICY(F) \
   F(CMP0003) \
@@ -43,12 +46,36 @@
 class cmGeneratorTarget;
 class cmTargetTraceDependencies;
 
-struct cmTargetLinkInformationMap:
-  public std::map<std::pair<cmTarget const* , std::string>,
-                  cmComputeLinkInformation*>
+// Basic information about each link item.
+class cmLinkItem: public std::string
 {
-  typedef std::map<std::pair<cmTarget const* , std::string>,
-                   cmComputeLinkInformation*> derived;
+  typedef std::string std_string;
+public:
+  cmLinkItem(): std_string(), Target(0) {}
+  cmLinkItem(const std_string& n,
+             cmTarget const* t): std_string(n), Target(t) {}
+  cmLinkItem(cmLinkItem const& r): std_string(r), Target(r.Target) {}
+  cmTarget const* Target;
+};
+class cmLinkImplItem: public cmLinkItem
+{
+public:
+  cmLinkImplItem(): cmLinkItem(), Backtrace(0), FromGenex(false) {}
+  cmLinkImplItem(std::string const& n,
+                 cmTarget const* t,
+                 cmListFileBacktrace const& bt,
+                 bool fromGenex):
+    cmLinkItem(n, t), Backtrace(bt), FromGenex(fromGenex) {}
+  cmLinkImplItem(cmLinkImplItem const& r):
+    cmLinkItem(r), Backtrace(r.Backtrace), FromGenex(r.FromGenex) {}
+  cmListFileBacktrace Backtrace;
+  bool FromGenex;
+};
+
+struct cmTargetLinkInformationMap:
+  public std::map<std::string, cmComputeLinkInformation*>
+{
+  typedef std::map<std::string, cmComputeLinkInformation*> derived;
   cmTargetLinkInformationMap() {}
   cmTargetLinkInformationMap(cmTargetLinkInformationMap const& r);
   ~cmTargetLinkInformationMap();
@@ -137,8 +164,7 @@
    * Get the list of the source files used by this target
    */
   void GetSourceFiles(std::vector<cmSourceFile*> &files,
-                      const std::string& config,
-                      cmTarget const* head = 0) const;
+                      const std::string& config) const;
   bool GetConfigCommonSourceFiles(std::vector<cmSourceFile*>& files) const;
 
   /**
@@ -155,16 +181,8 @@
   typedef std::pair<std::string, LinkLibraryType> LibraryID;
 
   typedef std::vector<LibraryID > LinkLibraryVectorType;
-  const LinkLibraryVectorType &GetLinkLibraries() const {
-  return this->LinkLibraries;}
   const LinkLibraryVectorType &GetOriginalLinkLibraries() const
     {return this->OriginalLinkLibraries;}
-  void GetDirectLinkLibraries(const std::string& config,
-                              std::vector<std::string> &,
-                              cmTarget const* head) const;
-  void GetInterfaceLinkLibraries(const std::string& config,
-                              std::vector<std::string> &,
-                              cmTarget const* head) const;
 
   /** Compute the link type to use for the given configuration.  */
   LinkLibraryType ComputeLinkType(const std::string& config) const;
@@ -221,6 +239,7 @@
   void AddUtility(const std::string& u, cmMakefile *makefile = 0);
   ///! Get the utilities used by this target
   std::set<std::string>const& GetUtilities() const { return this->Utilities; }
+  std::set<cmLinkItem>const& GetUtilityItems() const;
   cmListFileBacktrace const* GetUtilityBacktrace(const std::string& u) const;
 
   /** Finalize the target at the end of the Configure step.  */
@@ -246,16 +265,18 @@
 
   /** The link interface specifies transitive library dependencies and
       other information needed by targets that link to this target.  */
-  struct LinkInterface
+  struct LinkInterfaceLibraries
+  {
+    // Libraries listed in the interface.
+    std::vector<cmLinkItem> Libraries;
+  };
+  struct LinkInterface: public LinkInterfaceLibraries
   {
     // Languages whose runtime libraries must be linked.
     std::vector<std::string> Languages;
 
-    // Libraries listed in the interface.
-    std::vector<std::string> Libraries;
-
     // Shared library dependencies needed for linking on some platforms.
-    std::vector<std::string> SharedDeps;
+    std::vector<cmLinkItem> SharedDeps;
 
     // Number of repetitions of a strongly connected component of two
     // or more static libraries.
@@ -263,7 +284,7 @@
 
     // Libraries listed for other configurations.
     // Needed only for OLD behavior of CMP0003.
-    std::vector<std::string> WrongConfigLibraries;
+    std::vector<cmLinkItem> WrongConfigLibraries;
 
     bool ImplementationIsInterface;
 
@@ -274,35 +295,45 @@
       if the target cannot be linked.  */
   LinkInterface const* GetLinkInterface(const std::string& config,
                                         cmTarget const* headTarget) const;
-  LinkInterface const* GetLinkInterfaceLibraries(const std::string& config,
-                                        cmTarget const* headTarget) const;
-  void GetTransitivePropertyTargets(const std::string& config,
-                                        cmTarget const* headTarget,
-                                        std::vector<cmTarget*> &libs) const;
-  void GetTransitiveTargetClosure(const std::string& config,
-                                        cmTarget const* headTarget,
-                                        std::vector<cmTarget*> &libs) const;
+  LinkInterfaceLibraries const*
+    GetLinkInterfaceLibraries(const std::string& config,
+                              cmTarget const* headTarget,
+                              bool usage_requirements_only) const;
+
+  std::vector<cmTarget const*> const&
+    GetLinkImplementationClosure(const std::string& config) const;
+
+  struct CompatibleInterfaces
+  {
+    std::set<std::string> PropsBool;
+    std::set<std::string> PropsString;
+    std::set<std::string> PropsNumberMax;
+    std::set<std::string> PropsNumberMin;
+  };
+  CompatibleInterfaces const&
+    GetCompatibleInterfaces(std::string const& config) const;
 
   /** The link implementation specifies the direct library
       dependencies needed by the object files of the target.  */
-  struct LinkImplementation
+  struct LinkImplementationLibraries
   {
-    // Languages whose runtime libraries must be linked.
-    std::vector<std::string> Languages;
-
     // Libraries linked directly in this configuration.
-    std::vector<std::string> Libraries;
+    std::vector<cmLinkImplItem> Libraries;
 
     // Libraries linked directly in other configurations.
     // Needed only for OLD behavior of CMP0003.
-    std::vector<std::string> WrongConfigLibraries;
+    std::vector<cmLinkItem> WrongConfigLibraries;
   };
-  LinkImplementation const* GetLinkImplementation(const std::string& config,
-                                                  cmTarget const* head) const;
+  struct LinkImplementation: public LinkImplementationLibraries
+  {
+    // Languages whose runtime libraries must be linked.
+    std::vector<std::string> Languages;
+  };
+  LinkImplementation const*
+    GetLinkImplementation(const std::string& config) const;
 
-  LinkImplementation const* GetLinkImplementationLibraries(
-                                                  const std::string& config,
-                                                  cmTarget const* head) const;
+  LinkImplementationLibraries const*
+    GetLinkImplementationLibraries(const std::string& config) const;
 
   /** Link information from the transitive closure of the link
       implementation and the interfaces of its dependencies.  */
@@ -314,8 +345,9 @@
     // Languages whose runtime libraries must be linked.
     std::vector<std::string> Languages;
   };
-  LinkClosure const* GetLinkClosure(const std::string& config,
-                                    cmTarget const* head) const;
+  LinkClosure const* GetLinkClosure(const std::string& config) const;
+
+  cmTarget const* FindTargetToLink(std::string const& name) const;
 
   /** Strip off leading and trailing whitespace from an item named in
       the link dependencies of this target.  */
@@ -361,8 +393,7 @@
   GetTargetVersion(bool soversion, int& major, int& minor, int& patch) const;
 
   ///! Return the preferred linker language for this target
-  std::string GetLinkerLanguage(const std::string& config = "",
-                                cmTarget const* head = 0) const;
+  std::string GetLinkerLanguage(const std::string& config = "") const;
 
   /** Get the full name of the target according to the settings in its
       makefile.  */
@@ -446,8 +477,8 @@
     * install tree.  For example: "\@rpath/" or "\@loader_path/". */
   std::string GetInstallNameDirForInstallTree() const;
 
-  cmComputeLinkInformation* GetLinkInformation(const std::string& config,
-                                               cmTarget const* head = 0) const;
+  cmComputeLinkInformation*
+    GetLinkInformation(const std::string& config) const;
 
   // Get the properties
   cmPropertyMap &GetProperties() const { return this->Properties; }
@@ -473,8 +504,7 @@
   // information to forward these property changes to the targets
   // until we have per-target object file properties.
   void GetLanguages(std::set<std::string>& languages,
-                    std::string const& config,
-                    cmTarget const* head = 0) const;
+                    std::string const& config) const;
 
   /** Return whether this target is an executable with symbol exports
       enabled.  */
@@ -595,6 +625,11 @@
     return this->MaxLanguageStandards;
   }
 
+#if defined(_WIN32) && !defined(__CYGWIN__)
+  const LinkLibraryVectorType &GetLinkLibrariesForVS6() const {
+  return this->LinkLibrariesForVS6;}
+#endif
+
 private:
   bool HandleLocationPropertyPolicy(cmMakefile* context) const;
 
@@ -604,6 +639,7 @@
 
   std::vector<std::pair<TLLSignature, cmListFileBacktrace> > TLLCommands;
 
+#if defined(_WIN32) && !defined(__CYGWIN__)
   /**
    * A list of direct dependencies. Use in conjunction with DependencyMap.
    */
@@ -620,16 +656,16 @@
   /**
    * Inserts \a dep at the end of the dependency list of \a lib.
    */
-  void InsertDependency( DependencyMap& depMap,
-                         const LibraryID& lib,
-                         const LibraryID& dep);
+  void InsertDependencyForVS6( DependencyMap& depMap,
+                               const LibraryID& lib,
+                               const LibraryID& dep);
 
   /*
    * Deletes \a dep from the dependency list of \a lib.
    */
-  void DeleteDependency( DependencyMap& depMap,
-                         const LibraryID& lib,
-                         const LibraryID& dep);
+  void DeleteDependencyForVS6( DependencyMap& depMap,
+                               const LibraryID& lib,
+                               const LibraryID& dep);
 
   /**
    * Emits the library \a lib and all its dependencies into link_line.
@@ -639,21 +675,22 @@
    * link_line is in reverse order, in that the dependencies of a
    * library are listed before the library itself.
    */
-  void Emit( const LibraryID lib,
-             const DependencyMap& dep_map,
-             std::set<LibraryID>& emitted,
-             std::set<LibraryID>& visited,
-             DependencyList& link_line);
+  void EmitForVS6( const LibraryID lib,
+                   const DependencyMap& dep_map,
+                   std::set<LibraryID>& emitted,
+                   std::set<LibraryID>& visited,
+                   DependencyList& link_line);
 
   /**
    * Finds the dependencies for \a lib and inserts them into \a
    * dep_map.
    */
-  void GatherDependencies( const cmMakefile& mf,
-                           const LibraryID& lib,
-                           DependencyMap& dep_map);
+  void GatherDependenciesForVS6( const cmMakefile& mf,
+                                 const LibraryID& lib,
+                                 DependencyMap& dep_map);
 
-  void AnalyzeLibDependencies( const cmMakefile& mf );
+  void AnalyzeLibDependenciesForVS6( const cmMakefile& mf );
+#endif
 
   const char* GetSuffixVariableInternal(bool implib) const;
   const char* GetPrefixVariableInternal(bool implib) const;
@@ -694,17 +731,18 @@
                                        bool contentOnly) const;
 
   void GetSourceFiles(std::vector<std::string> &files,
-                      const std::string& config,
-                      cmTarget const* head = 0) const;
+                      const std::string& config) const;
 private:
   std::string Name;
   std::vector<cmCustomCommand> PreBuildCommands;
   std::vector<cmCustomCommand> PreLinkCommands;
   std::vector<cmCustomCommand> PostBuildCommands;
   TargetType TargetTypeValue;
-  LinkLibraryVectorType LinkLibraries;
   LinkLibraryVectorType PrevLinkedLibraries;
-  bool LinkLibrariesAnalyzed;
+#if defined(_WIN32) && !defined(__CYGWIN__)
+  LinkLibraryVectorType LinkLibrariesForVS6;
+  bool LinkLibrariesForVS6Analyzed;
+#endif
   std::vector<std::string> LinkDirectories;
   std::set<std::string> LinkDirectoriesEmmitted;
   bool HaveInstallRule;
@@ -717,6 +755,7 @@
   mutable cmPropertyMap Properties;
   LinkLibraryVectorType OriginalLinkLibraries;
   bool DLLPlatform;
+  bool IsAndroid;
   bool IsApple;
   bool IsImportedTarget;
   mutable bool DebugIncludesDone;
@@ -740,10 +779,9 @@
 
   // Cache import information from properties for each configuration.
   struct ImportInfo;
-  ImportInfo const* GetImportInfo(const std::string& config,
-                                        cmTarget const* workingTarget) const;
-  void ComputeImportInfo(std::string const& desired_config, ImportInfo& info,
-                                        cmTarget const* head) const;
+  ImportInfo const* GetImportInfo(const std::string& config) const;
+  void ComputeImportInfo(std::string const& desired_config,
+                         ImportInfo& info) const;
 
   // Cache target compile paths for each configuration.
   struct CompileInfo;
@@ -753,19 +791,22 @@
   void CheckPropertyCompatibility(cmComputeLinkInformation *info,
                                   const std::string& config) const;
 
-  const char* ComputeLinkInterfaceLibraries(const std::string& config,
-                                            LinkInterface& iface,
-                                            cmTarget const* head,
-                                            bool &exists) const;
+  LinkInterface const*
+    GetImportLinkInterface(const std::string& config, cmTarget const* head,
+                           bool usage_requirements_only) const;
 
-  void ComputeLinkImplementation(const std::string& config,
-                                 LinkImplementation& impl,
-                                 cmTarget const* head) const;
-  void ComputeLinkImplementationLanguages(const std::string& config,
-                                          LinkImplementation& impl,
-                                          cmTarget const* head) const;
-  void ComputeLinkClosure(const std::string& config, LinkClosure& lc,
-                          cmTarget const* head) const;
+  LinkImplementationLibraries const*
+    GetLinkImplementationLibrariesInternal(const std::string& config,
+                                           cmTarget const* head) const;
+  void ComputeLinkClosure(const std::string& config, LinkClosure& lc) const;
+
+  void ExpandLinkItems(std::string const& prop, std::string const& value,
+                       std::string const& config, cmTarget const* headTarget,
+                       bool usage_requirements_only,
+                       std::vector<cmLinkItem>& items,
+                       bool& hadHeadSensitiveCondition) const;
+  void LookupLinkItems(std::vector<std::string> const& names,
+                       std::vector<cmLinkItem>& items) const;
 
   std::string ProcessSourceItemCMP0049(const std::string& s);
 
@@ -803,7 +844,11 @@
   mutable bool LinkImplementationLanguageIsContextDependent;
 };
 
+#ifdef CMAKE_BUILD_WITH_CMAKE
+typedef cmsys::hash_map<std::string,cmTarget> cmTargets;
+#else
 typedef std::map<std::string,cmTarget> cmTargets;
+#endif
 
 class cmTargetSet: public std::set<std::string> {};
 class cmTargetManifest: public std::map<std::string, cmTargetSet> {};
diff --git a/Source/cmTimestamp.cxx b/Source/cmTimestamp.cxx
index ac26503..6fd6ab7 100644
--- a/Source/cmTimestamp.cxx
+++ b/Source/cmTimestamp.cxx
@@ -33,15 +33,13 @@
 std::string cmTimestamp::FileModificationTime(const char* path,
   const std::string& formatString, bool utcFlag)
 {
-  struct stat info;
-  memset(&info, 0, sizeof(info));
-
-  if(stat(path, &info) != 0)
+  if(!cmsys::SystemTools::FileExists(path))
     {
     return std::string();
     }
 
-  return CreateTimestampFromTimeT(info.st_mtime, formatString, utcFlag);
+  time_t mtime = cmsys::SystemTools::ModifiedTime(path);
+  return CreateTimestampFromTimeT(mtime, formatString, utcFlag);
 }
 
 //----------------------------------------------------------------------------
diff --git a/Source/cmUuid.cxx b/Source/cmUuid.cxx
new file mode 100644
index 0000000..8b5b7ae
--- /dev/null
+++ b/Source/cmUuid.cxx
@@ -0,0 +1,214 @@
+/*============================================================================
+  CMake - Cross Platform Makefile Generator
+  Copyright 2014 Kitware, Inc., Insight Software Consortium
+
+  Distributed under the OSI-approved BSD License (the "License");
+  see accompanying file Copyright.txt for details.
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the License for more information.
+============================================================================*/
+#include "cmUuid.h"
+
+#include <string.h>
+
+#include <cmsys/MD5.h>
+#include "cm_sha2.h"
+
+cmUuid::cmUuid()
+{
+  Groups.push_back(4);
+  Groups.push_back(2);
+  Groups.push_back(2);
+  Groups.push_back(2);
+  Groups.push_back(6);
+}
+
+std::string cmUuid::FromMd5(std::vector<unsigned char> const& uuidNamespace,
+  std::string const& name) const
+{
+  std::vector<unsigned char> hashInput;
+  this->CreateHashInput(uuidNamespace, name, hashInput);
+
+  cmsysMD5_s *md5 = cmsysMD5_New();
+  cmsysMD5_Initialize(md5);
+  cmsysMD5_Append(md5, &hashInput[0], int(hashInput.size()));
+
+  unsigned char digest[16] = {0};
+  cmsysMD5_Finalize(md5, digest);
+
+  cmsysMD5_Delete(md5);
+
+  return this->FromDigest(digest, 3);
+}
+
+std::string cmUuid::FromSha1(std::vector<unsigned char> const& uuidNamespace,
+    std::string const& name) const
+{
+  std::vector<unsigned char> hashInput;
+  this->CreateHashInput(uuidNamespace, name, hashInput);
+
+  SHA_CTX *sha = new SHA_CTX;
+  SHA1_Init(sha);
+  SHA1_Update(sha, &hashInput[0], hashInput.size());
+
+  unsigned char digest[SHA1_DIGEST_LENGTH] = {0};
+  SHA1_Final(digest, sha);
+
+  delete sha;
+
+  return this->FromDigest(digest, 5);
+}
+
+void cmUuid::CreateHashInput(std::vector<unsigned char> const& uuidNamespace,
+  std::string const& name, std::vector<unsigned char> &output) const
+{
+  output = uuidNamespace;
+
+  if(name.size())
+    {
+    output.resize(output.size() + name.size());
+
+    memcpy(&output[0] + uuidNamespace.size(),
+      name.c_str(), name.size());
+    }
+}
+
+std::string cmUuid::FromDigest(
+  const unsigned char* digest, unsigned char version) const
+{
+  typedef unsigned char byte_t;
+
+  byte_t uuid[16] = {0};
+  memcpy(uuid, digest, 16);
+
+  uuid[6] &= 0xF;
+  uuid[6] |= byte_t(version << 4);
+
+  uuid[8] &= 0x3F;
+  uuid[8] |= 0x80;
+
+  return this->BinaryToString(uuid);
+}
+
+bool cmUuid::StringToBinary(std::string const& input,
+  std::vector<unsigned char> &output) const
+{
+  output.clear();
+  output.reserve(16);
+
+  if(input.length() != 36)
+    {
+    return false;
+    }
+  size_t index = 0;
+  for(size_t i = 0; i < this->Groups.size(); ++i)
+    {
+    if(i != 0 && input[index++] != '-')
+      {
+      return false;
+      }
+    size_t digits = this->Groups[i] * 2;
+    if(!StringToBinaryImpl(input.substr(index, digits), output))
+      {
+      return false;
+      }
+
+    index += digits;
+    }
+
+  return true;
+}
+
+std::string cmUuid::BinaryToString(const unsigned char* input) const
+{
+  std::string output;
+
+  size_t inputIndex = 0;
+  for(size_t i = 0; i < this->Groups.size(); ++i)
+    {
+    if(i != 0)
+      {
+      output += '-';
+      }
+
+    size_t bytes = this->Groups[i];
+    for(size_t j = 0; j < bytes; ++j)
+      {
+      unsigned char byte = input[inputIndex++];
+      output += this->ByteToHex(byte);
+      }
+    }
+
+  return output;
+}
+
+std::string cmUuid::ByteToHex(unsigned char byte) const
+{
+  std::string result;
+  for(int i = 0; i < 2; ++i)
+    {
+    unsigned char rest = byte % 16;
+    byte /= 16;
+
+    char c = (rest < 0xA) ?
+      char('0' + rest) :
+      char('a' + (rest - 0xA));
+
+    result = c + result;
+    }
+
+  return result;
+}
+
+bool cmUuid::StringToBinaryImpl(std::string const& input,
+  std::vector<unsigned char> &output) const
+{
+  if(input.size()%2)
+    {
+    return false;
+    }
+
+  for(size_t i = 0; i < input.size(); i +=2)
+    {
+    char c1 = 0;
+    if(!IntFromHexDigit(input[i], c1))
+      {
+      return false;
+      }
+
+    char c2 = 0;
+    if(!IntFromHexDigit(input[i + 1], c2))
+      {
+      return false;
+      }
+
+    output.push_back(char(c1 << 4 | c2));
+    }
+
+  return true;
+}
+
+bool cmUuid::IntFromHexDigit(char input, char& output) const
+{
+  if(input >= '0' && input <= '9')
+    {
+    output = char(input - '0');
+    return true;
+    }
+  else if(input >= 'a' && input <= 'f')
+    {
+    output = char(input - 'a' + 0xA);
+    return true;
+    }
+  else if(input >= 'A' && input <= 'F')
+    {
+    output = char(input - 'A' + 0xA);
+    return true;
+    }
+  else
+    {
+    return false;
+    }
+}
diff --git a/Source/cmUuid.h b/Source/cmUuid.h
new file mode 100644
index 0000000..0dda357
--- /dev/null
+++ b/Source/cmUuid.h
@@ -0,0 +1,55 @@
+/*============================================================================
+  CMake - Cross Platform Makefile Generator
+  Copyright 2014 Kitware, Inc., Insight Software Consortium
+
+  Distributed under the OSI-approved BSD License (the "License");
+  see accompanying file Copyright.txt for details.
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the License for more information.
+============================================================================*/
+#ifndef cmUuid_h
+#define cmUuid_h
+
+#include "cmStandardIncludes.h"
+
+/** \class cmUuid
+ * \brief Utility class to generate UUIDs as defined by RFC4122
+ *
+ */
+class cmUuid
+{
+public:
+  cmUuid();
+
+  std::string FromMd5(std::vector<unsigned char> const& uuidNamespace,
+    std::string const& name) const;
+
+  std::string FromSha1(std::vector<unsigned char> const& uuidNamespace,
+    std::string const& name) const;
+
+  bool StringToBinary(std::string const& input,
+    std::vector<unsigned char> &output) const;
+
+private:
+  std::string ByteToHex(unsigned char byte) const;
+
+  void CreateHashInput(std::vector<unsigned char> const& uuidNamespace,
+    std::string const& name, std::vector<unsigned char> &output) const;
+
+  std::string FromDigest(const unsigned char* digest,
+    unsigned char version) const;
+
+  bool StringToBinaryImpl(std::string const& input,
+    std::vector<unsigned char> &output) const;
+
+  std::string BinaryToString(const unsigned char* input) const;
+
+  bool IntFromHexDigit(char input, char& output) const;
+
+  std::vector<int> Groups;
+};
+
+
+#endif
diff --git a/Source/cmVS10MASMFlagTable.h b/Source/cmVS10MASMFlagTable.h
new file mode 100644
index 0000000..8fb6f33
--- /dev/null
+++ b/Source/cmVS10MASMFlagTable.h
@@ -0,0 +1,96 @@
+static cmVS7FlagTable cmVS10MASMFlagTable[] =
+{
+
+  //Enum Properties
+  {"PreserveIdentifierCase", "",
+   "Default", "0", 0},
+  {"PreserveIdentifierCase", "/Cp",
+   "Preserves Identifier Case (/Cp)", "1", 0},
+  {"PreserveIdentifierCase", "/Cu",
+   "Maps all identifiers to upper case. (/Cu)", "2", 0},
+  {"PreserveIdentifierCase", "/Cx",
+   "Preserves case in public and extern symbols. (/Cx)", "3", 0},
+
+  {"WarningLevel", "/W0",
+   "Warning Level 0 (/W0)", "0", 0},
+  {"WarningLevel", "/W1",
+   "Warning Level 1 (/W1)", "1", 0},
+  {"WarningLevel", "/W2",
+   "Warning Level 2 (/W2)", "2", 0},
+  {"WarningLevel", "/W3",
+   "Warning Level 3 (/W3)", "3", 0},
+
+  {"PackAlignmentBoundary", "",
+   "Default", "0", 0},
+  {"PackAlignmentBoundary", "/Zp1",
+   "One Byte Boundary (/Zp1)", "1", 0},
+  {"PackAlignmentBoundary", "/Zp2",
+   "Two Byte Boundary (/Zp2)", "2", 0},
+  {"PackAlignmentBoundary", "/Zp4",
+   "Four Byte Boundary (/Zp4)", "3", 0},
+  {"PackAlignmentBoundary", "/Zp8",
+   "Eight Byte Boundary (/Zp8)", "4", 0},
+  {"PackAlignmentBoundary", "/Zp16",
+   "Sixteen Byte Boundary (/Zp16)", "5", 0},
+
+  {"CallingConvention", "",
+   "Default", "0", 0},
+  {"CallingConvention", "/Gd",
+   "Use C-style Calling Convention (/Gd)", "1", 0},
+  {"CallingConvention", "/Gz",
+   "Use stdcall Calling Convention (/Gz)", "2", 0},
+  {"CallingConvention", "/Gc",
+   "Use Pascal Calling Convention (/Gc)", "3", 0},
+
+  {"ErrorReporting", "/errorReport:prompt",
+   "Prompt to send report immediately (/errorReport:prompt)", "0", 0},
+  {"ErrorReporting", "/errorReport:queue",
+   "Prompt to send report at the next logon (/errorReport:queue)", "1", 0},
+  {"ErrorReporting", "/errorReport:send",
+   "Automatically send report (/errorReport:send)", "2", 0},
+  {"ErrorReporting", "/errorReport:none",
+   "Do not send report (/errorReport:none)", "3", 0},
+
+
+  //Bool Properties
+  {"NoLogo", "/nologo", "", "true", 0},
+  {"GeneratePreprocessedSourceListing", "/EP", "", "true", 0},
+  {"ListAllAvailableInformation", "/Sa", "", "true", 0},
+  {"UseSafeExceptionHandlers", "/safeseh", "", "true", 0},
+  {"AddFirstPassListing", "/Sf", "", "true", 0},
+  {"EnableAssemblyGeneratedCodeListing", "/Sg", "", "true", 0},
+  {"DisableSymbolTable", "/Sn", "", "true", 0},
+  {"EnableFalseConditionalsInListing", "/Sx", "", "true", 0},
+  {"TreatWarningsAsErrors", "/WX", "", "true", 0},
+  {"MakeAllSymbolsPublic", "/Zf", "", "true", 0},
+  {"GenerateDebugInformation", "/Zi", "", "true", 0},
+  {"EnableMASM51Compatibility", "/Zm", "", "true", 0},
+  {"PerformSyntaxCheckOnly", "/Zs", "", "true", 0},
+
+  //Bool Properties With Argument
+
+  //String List Properties
+  {"PreprocessorDefinitions", "/D",
+   "Preprocessor Definitions",
+   "", cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable},
+  {"IncludePaths", "/I",
+   "Include Paths",
+   "", cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable},
+  {"BrowseFile", "/FR",
+   "Generate Browse Information File",
+   "", cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable},
+  // Skip [AdditionalDependencies] - no command line Switch.
+
+  //String Properties
+  // Skip [Inputs] - no command line Switch.
+  {"ObjectFileName", "/Fo",
+   "Object File Name",
+   "", cmVS7FlagTable::UserValue},
+  {"AssembledCodeListingFile", "/Fl",
+   "Assembled Code Listing File",
+   "", cmVS7FlagTable::UserValue},
+  // Skip [CommandLineTemplate] - no command line Switch.
+  // Skip [ExecutionDescription] - no command line Switch.
+  // Skip [AdditionalOptions] - no command line Switch.
+  {0,0,0,0,0}
+};
diff --git a/Source/cmVS10RCFlagTable.h b/Source/cmVS10RCFlagTable.h
new file mode 100644
index 0000000..9049986
--- /dev/null
+++ b/Source/cmVS10RCFlagTable.h
@@ -0,0 +1,7 @@
+static cmVS7FlagTable cmVS10RCFlagTable[] =
+{
+  //Bool Properties
+  {"NullTerminateStrings", "n", "", "true", 0},
+
+  {0,0,0,0,0}
+};
diff --git a/Source/cmVS11MASMFlagTable.h b/Source/cmVS11MASMFlagTable.h
new file mode 100644
index 0000000..2ff95ad
--- /dev/null
+++ b/Source/cmVS11MASMFlagTable.h
@@ -0,0 +1,96 @@
+static cmVS7FlagTable cmVS11MASMFlagTable[] =
+{
+
+  //Enum Properties
+  {"PreserveIdentifierCase", "",
+   "Default", "0", 0},
+  {"PreserveIdentifierCase", "/Cp",
+   "Preserves Identifier Case (/Cp)", "1", 0},
+  {"PreserveIdentifierCase", "/Cu",
+   "Maps all identifiers to upper case. (/Cu)", "2", 0},
+  {"PreserveIdentifierCase", "/Cx",
+   "Preserves case in public and extern symbols. (/Cx)", "3", 0},
+
+  {"WarningLevel", "/W0",
+   "Warning Level 0 (/W0)", "0", 0},
+  {"WarningLevel", "/W1",
+   "Warning Level 1 (/W1)", "1", 0},
+  {"WarningLevel", "/W2",
+   "Warning Level 2 (/W2)", "2", 0},
+  {"WarningLevel", "/W3",
+   "Warning Level 3 (/W3)", "3", 0},
+
+  {"PackAlignmentBoundary", "",
+   "Default", "0", 0},
+  {"PackAlignmentBoundary", "/Zp1",
+   "One Byte Boundary (/Zp1)", "1", 0},
+  {"PackAlignmentBoundary", "/Zp2",
+   "Two Byte Boundary (/Zp2)", "2", 0},
+  {"PackAlignmentBoundary", "/Zp4",
+   "Four Byte Boundary (/Zp4)", "3", 0},
+  {"PackAlignmentBoundary", "/Zp8",
+   "Eight Byte Boundary (/Zp8)", "4", 0},
+  {"PackAlignmentBoundary", "/Zp16",
+   "Sixteen Byte Boundary (/Zp16)", "5", 0},
+
+  {"CallingConvention", "",
+   "Default", "0", 0},
+  {"CallingConvention", "/Gd",
+   "Use C-style Calling Convention (/Gd)", "1", 0},
+  {"CallingConvention", "/Gz",
+   "Use stdcall Calling Convention (/Gz)", "2", 0},
+  {"CallingConvention", "/Gc",
+   "Use Pascal Calling Convention (/Gc)", "3", 0},
+
+  {"ErrorReporting", "/errorReport:prompt",
+   "Prompt to send report immediately (/errorReport:prompt)", "0", 0},
+  {"ErrorReporting", "/errorReport:queue",
+   "Prompt to send report at the next logon (/errorReport:queue)", "1", 0},
+  {"ErrorReporting", "/errorReport:send",
+   "Automatically send report (/errorReport:send)", "2", 0},
+  {"ErrorReporting", "/errorReport:none",
+   "Do not send report (/errorReport:none)", "3", 0},
+
+
+  //Bool Properties
+  {"NoLogo", "/nologo", "", "true", 0},
+  {"GeneratePreprocessedSourceListing", "/EP", "", "true", 0},
+  {"ListAllAvailableInformation", "/Sa", "", "true", 0},
+  {"UseSafeExceptionHandlers", "/safeseh", "", "true", 0},
+  {"AddFirstPassListing", "/Sf", "", "true", 0},
+  {"EnableAssemblyGeneratedCodeListing", "/Sg", "", "true", 0},
+  {"DisableSymbolTable", "/Sn", "", "true", 0},
+  {"EnableFalseConditionalsInListing", "/Sx", "", "true", 0},
+  {"TreatWarningsAsErrors", "/WX", "", "true", 0},
+  {"MakeAllSymbolsPublic", "/Zf", "", "true", 0},
+  {"GenerateDebugInformation", "/Zi", "", "true", 0},
+  {"EnableMASM51Compatibility", "/Zm", "", "true", 0},
+  {"PerformSyntaxCheckOnly", "/Zs", "", "true", 0},
+
+  //Bool Properties With Argument
+
+  //String List Properties
+  {"PreprocessorDefinitions", "/D",
+   "Preprocessor Definitions",
+   "", cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable},
+  {"IncludePaths", "/I",
+   "Include Paths",
+   "", cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable},
+  {"BrowseFile", "/FR",
+   "Generate Browse Information File",
+   "", cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable},
+  // Skip [AdditionalDependencies] - no command line Switch.
+
+  //String Properties
+  // Skip [Inputs] - no command line Switch.
+  {"ObjectFileName", "/Fo",
+   "Object File Name",
+   "", cmVS7FlagTable::UserValue},
+  {"AssembledCodeListingFile", "/Fl",
+   "Assembled Code Listing File",
+   "", cmVS7FlagTable::UserValue},
+  // Skip [CommandLineTemplate] - no command line Switch.
+  // Skip [ExecutionDescription] - no command line Switch.
+  // Skip [AdditionalOptions] - no command line Switch.
+  {0,0,0,0,0}
+};
diff --git a/Source/cmVS11RCFlagTable.h b/Source/cmVS11RCFlagTable.h
new file mode 100644
index 0000000..a7d2de1
--- /dev/null
+++ b/Source/cmVS11RCFlagTable.h
@@ -0,0 +1,7 @@
+static cmVS7FlagTable cmVS11RCFlagTable[] =
+{
+  //Bool Properties
+  {"NullTerminateStrings", "n", "", "true", 0},
+
+  {0,0,0,0,0}
+};
diff --git a/Source/cmVS12MASMFlagTable.h b/Source/cmVS12MASMFlagTable.h
new file mode 100644
index 0000000..74d529c
--- /dev/null
+++ b/Source/cmVS12MASMFlagTable.h
@@ -0,0 +1,96 @@
+static cmVS7FlagTable cmVS12MASMFlagTable[] =
+{
+
+  //Enum Properties
+  {"PreserveIdentifierCase", "",
+   "Default", "0", 0},
+  {"PreserveIdentifierCase", "/Cp",
+   "Preserves Identifier Case (/Cp)", "1", 0},
+  {"PreserveIdentifierCase", "/Cu",
+   "Maps all identifiers to upper case. (/Cu)", "2", 0},
+  {"PreserveIdentifierCase", "/Cx",
+   "Preserves case in public and extern symbols. (/Cx)", "3", 0},
+
+  {"WarningLevel", "/W0",
+   "Warning Level 0 (/W0)", "0", 0},
+  {"WarningLevel", "/W1",
+   "Warning Level 1 (/W1)", "1", 0},
+  {"WarningLevel", "/W2",
+   "Warning Level 2 (/W2)", "2", 0},
+  {"WarningLevel", "/W3",
+   "Warning Level 3 (/W3)", "3", 0},
+
+  {"PackAlignmentBoundary", "",
+   "Default", "0", 0},
+  {"PackAlignmentBoundary", "/Zp1",
+   "One Byte Boundary (/Zp1)", "1", 0},
+  {"PackAlignmentBoundary", "/Zp2",
+   "Two Byte Boundary (/Zp2)", "2", 0},
+  {"PackAlignmentBoundary", "/Zp4",
+   "Four Byte Boundary (/Zp4)", "3", 0},
+  {"PackAlignmentBoundary", "/Zp8",
+   "Eight Byte Boundary (/Zp8)", "4", 0},
+  {"PackAlignmentBoundary", "/Zp16",
+   "Sixteen Byte Boundary (/Zp16)", "5", 0},
+
+  {"CallingConvention", "",
+   "Default", "0", 0},
+  {"CallingConvention", "/Gd",
+   "Use C-style Calling Convention (/Gd)", "1", 0},
+  {"CallingConvention", "/Gz",
+   "Use stdcall Calling Convention (/Gz)", "2", 0},
+  {"CallingConvention", "/Gc",
+   "Use Pascal Calling Convention (/Gc)", "3", 0},
+
+  {"ErrorReporting", "/errorReport:prompt",
+   "Prompt to send report immediately (/errorReport:prompt)", "0", 0},
+  {"ErrorReporting", "/errorReport:queue",
+   "Prompt to send report at the next logon (/errorReport:queue)", "1", 0},
+  {"ErrorReporting", "/errorReport:send",
+   "Automatically send report (/errorReport:send)", "2", 0},
+  {"ErrorReporting", "/errorReport:none",
+   "Do not send report (/errorReport:none)", "3", 0},
+
+
+  //Bool Properties
+  {"NoLogo", "/nologo", "", "true", 0},
+  {"GeneratePreprocessedSourceListing", "/EP", "", "true", 0},
+  {"ListAllAvailableInformation", "/Sa", "", "true", 0},
+  {"UseSafeExceptionHandlers", "/safeseh", "", "true", 0},
+  {"AddFirstPassListing", "/Sf", "", "true", 0},
+  {"EnableAssemblyGeneratedCodeListing", "/Sg", "", "true", 0},
+  {"DisableSymbolTable", "/Sn", "", "true", 0},
+  {"EnableFalseConditionalsInListing", "/Sx", "", "true", 0},
+  {"TreatWarningsAsErrors", "/WX", "", "true", 0},
+  {"MakeAllSymbolsPublic", "/Zf", "", "true", 0},
+  {"GenerateDebugInformation", "/Zi", "", "true", 0},
+  {"EnableMASM51Compatibility", "/Zm", "", "true", 0},
+  {"PerformSyntaxCheckOnly", "/Zs", "", "true", 0},
+
+  //Bool Properties With Argument
+
+  //String List Properties
+  {"PreprocessorDefinitions", "/D",
+   "Preprocessor Definitions",
+   "", cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable},
+  {"IncludePaths", "/I",
+   "Include Paths",
+   "", cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable},
+  {"BrowseFile", "/FR",
+   "Generate Browse Information File",
+   "", cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable},
+  // Skip [AdditionalDependencies] - no command line Switch.
+
+  //String Properties
+  // Skip [Inputs] - no command line Switch.
+  {"ObjectFileName", "/Fo",
+   "Object File Name",
+   "", cmVS7FlagTable::UserValue},
+  {"AssembledCodeListingFile", "/Fl",
+   "Assembled Code Listing File",
+   "", cmVS7FlagTable::UserValue},
+  // Skip [CommandLineTemplate] - no command line Switch.
+  // Skip [ExecutionDescription] - no command line Switch.
+  // Skip [AdditionalOptions] - no command line Switch.
+  {0,0,0,0,0}
+};
diff --git a/Source/cmVS12RCFlagTable.h b/Source/cmVS12RCFlagTable.h
new file mode 100644
index 0000000..1551c66
--- /dev/null
+++ b/Source/cmVS12RCFlagTable.h
@@ -0,0 +1,7 @@
+static cmVS7FlagTable cmVS12RCFlagTable[] =
+{
+  //Bool Properties
+  {"NullTerminateStrings", "n", "", "true", 0},
+
+  {0,0,0,0,0}
+};
diff --git a/Source/cmVS14CLFlagTable.h b/Source/cmVS14CLFlagTable.h
new file mode 100644
index 0000000..422f47b
--- /dev/null
+++ b/Source/cmVS14CLFlagTable.h
@@ -0,0 +1,296 @@
+static cmVS7FlagTable cmVS14CLFlagTable[] =
+{
+
+  //Enum Properties
+  {"DebugInformationFormat", "",
+   "None", "None", 0},
+  {"DebugInformationFormat", "Z7",
+   "C7 compatible", "OldStyle", 0},
+  {"DebugInformationFormat", "Zi",
+   "Program Database", "ProgramDatabase", 0},
+  {"DebugInformationFormat", "ZI",
+   "Program Database for Edit And Continue", "EditAndContinue", 0},
+
+  {"WarningLevel", "W0",
+   "Turn Off All Warnings", "TurnOffAllWarnings", 0},
+  {"WarningLevel", "W1",
+   "Level1", "Level1", 0},
+  {"WarningLevel", "W2",
+   "Level2", "Level2", 0},
+  {"WarningLevel", "W3",
+   "Level3", "Level3", 0},
+  {"WarningLevel", "W4",
+   "Level4", "Level4", 0},
+  {"WarningLevel", "Wall",
+   "EnableAllWarnings", "EnableAllWarnings", 0},
+
+  {"Optimization", "",
+   "Custom", "Custom", 0},
+  {"Optimization", "Od",
+   "Disabled", "Disabled", 0},
+  {"Optimization", "O1",
+   "Minimize Size", "MinSpace", 0},
+  {"Optimization", "O2",
+   "Maximize Speed", "MaxSpeed", 0},
+  {"Optimization", "Ox",
+   "Full Optimization", "Full", 0},
+
+  {"InlineFunctionExpansion", "",
+   "Default", "Default", 0},
+  {"InlineFunctionExpansion", "Ob0",
+   "Disabled", "Disabled", 0},
+  {"InlineFunctionExpansion", "Ob1",
+   "Only __inline", "OnlyExplicitInline", 0},
+  {"InlineFunctionExpansion", "Ob2",
+   "Any Suitable", "AnySuitable", 0},
+
+  {"FavorSizeOrSpeed", "Os",
+   "Favor small code", "Size", 0},
+  {"FavorSizeOrSpeed", "Ot",
+   "Favor fast code", "Speed", 0},
+  {"FavorSizeOrSpeed", "",
+   "Neither", "Neither", 0},
+
+  {"ExceptionHandling", "EHa",
+   "Yes with SEH Exceptions", "Async", 0},
+  {"ExceptionHandling", "EHsc",
+   "Yes", "Sync", 0},
+  {"ExceptionHandling", "EHs",
+   "Yes with Extern C functions", "SyncCThrow", 0},
+  {"ExceptionHandling", "",
+   "No", "false", 0},
+
+  {"BasicRuntimeChecks", "RTCs",
+   "Stack Frames", "StackFrameRuntimeCheck", 0},
+  {"BasicRuntimeChecks", "RTCu",
+   "Uninitialized variables", "UninitializedLocalUsageCheck", 0},
+  {"BasicRuntimeChecks", "RTC1",
+   "Both (/RTC1, equiv. to /RTCsu)", "EnableFastChecks", 0},
+  {"BasicRuntimeChecks", "",
+   "Default", "Default", 0},
+
+  {"RuntimeLibrary", "MT",
+   "Multi-threaded", "MultiThreaded", 0},
+  {"RuntimeLibrary", "MTd",
+   "Multi-threaded Debug", "MultiThreadedDebug", 0},
+  {"RuntimeLibrary", "MD",
+   "Multi-threaded DLL", "MultiThreadedDLL", 0},
+  {"RuntimeLibrary", "MDd",
+   "Multi-threaded Debug DLL", "MultiThreadedDebugDLL", 0},
+
+  {"StructMemberAlignment", "Zp1",
+   "1 Byte", "1Byte", 0},
+  {"StructMemberAlignment", "Zp2",
+   "2 Bytes", "2Bytes", 0},
+  {"StructMemberAlignment", "Zp4",
+   "4 Byte", "4Bytes", 0},
+  {"StructMemberAlignment", "Zp8",
+   "8 Bytes", "8Bytes", 0},
+  {"StructMemberAlignment", "Zp16",
+   "16 Bytes", "16Bytes", 0},
+  {"StructMemberAlignment", "",
+   "Default", "Default", 0},
+
+  {"BufferSecurityCheck", "GS-",
+   "Disable Security Check", "false", 0},
+  {"BufferSecurityCheck", "GS",
+   "Enable Security Check", "true", 0},
+
+  {"EnableEnhancedInstructionSet", "arch:SSE",
+   "Streaming SIMD Extensions", "StreamingSIMDExtensions", 0},
+  {"EnableEnhancedInstructionSet", "arch:SSE2",
+   "Streaming SIMD Extensions 2", "StreamingSIMDExtensions2", 0},
+  {"EnableEnhancedInstructionSet", "arch:AVX",
+   "Advanced Vector Extensions", "AdvancedVectorExtensions", 0},
+  {"EnableEnhancedInstructionSet", "arch:AVX2",
+   "Advanced Vector Extensions 2", "AdvancedVectorExtensions2", 0},
+  {"EnableEnhancedInstructionSet", "arch:IA32",
+   "No Enhanced Instructions", "NoExtensions", 0},
+  {"EnableEnhancedInstructionSet", "",
+   "Not Set", "NotSet", 0},
+
+  {"FloatingPointModel", "fp:precise",
+   "Precise", "Precise", 0},
+  {"FloatingPointModel", "fp:strict",
+   "Strict", "Strict", 0},
+  {"FloatingPointModel", "fp:fast",
+   "Fast", "Fast", 0},
+
+  {"PrecompiledHeader", "Yc",
+   "Create", "Create",
+   cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue},
+  {"PrecompiledHeader", "Yu",
+   "Use", "Use",
+   cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue},
+  {"PrecompiledHeader", "",
+   "Not Using Precompiled Headers", "NotUsing", 0},
+
+  {"AssemblerOutput", "",
+   "No Listing", "NoListing", 0},
+  {"AssemblerOutput", "FA",
+   "Assembly-Only Listing", "AssemblyCode", 0},
+  {"AssemblerOutput", "FAc",
+   "Assembly With Machine Code", "AssemblyAndMachineCode", 0},
+  {"AssemblerOutput", "FAs",
+   "Assembly With Source Code", "AssemblyAndSourceCode", 0},
+  {"AssemblerOutput", "FAcs",
+   "Assembly, Machine Code and Source", "All", 0},
+
+  {"CallingConvention", "Gd",
+   "__cdecl", "Cdecl", 0},
+  {"CallingConvention", "Gr",
+   "__fastcall", "FastCall", 0},
+  {"CallingConvention", "Gz",
+   "__stdcall", "StdCall", 0},
+  {"CallingConvention", "Gv",
+   "__vectorcall", "VectorCall", 0},
+
+  {"CompileAs", "",
+   "Default", "Default", 0},
+  {"CompileAs", "TC",
+   "Compile as C Code", "CompileAsC", 0},
+  {"CompileAs", "TP",
+   "Compile as C++ Code", "CompileAsCpp", 0},
+
+  {"ErrorReporting", "errorReport:none",
+   "Do Not Send Report", "None", 0},
+  {"ErrorReporting", "errorReport:prompt",
+   "Prompt Immediately", "Prompt", 0},
+  {"ErrorReporting", "errorReport:queue",
+   "Queue For Next Login", "Queue", 0},
+  {"ErrorReporting", "errorReport:send",
+   "Send Automatically", "Send", 0},
+
+  {"CompileAsManaged", "",
+   "No Common Language RunTime Support", "false", 0},
+  {"CompileAsManaged", "clr",
+   "Common Language RunTime Support", "true", 0},
+  {"CompileAsManaged", "clr:pure",
+   "Pure MSIL Common Language RunTime Support", "Pure", 0},
+  {"CompileAsManaged", "clr:safe",
+   "Safe MSIL Common Language RunTime Support", "Safe", 0},
+  {"CompileAsManaged", "clr:oldSyntax",
+   "Common Language RunTime Support, Old Syntax", "OldSyntax", 0},
+
+
+  //Bool Properties
+  {"CompileAsWinRT", "ZW", "", "true", 0},
+  {"WinRTNoStdLib", "ZW:nostdlib", "", "true", 0},
+  {"SuppressStartupBanner", "nologo", "", "true", 0},
+  {"TreatWarningAsError", "WX-", "", "false", 0},
+  {"TreatWarningAsError", "WX", "", "true", 0},
+  {"SDLCheck", "sdl-", "", "false", 0},
+  {"SDLCheck", "sdl", "", "true", 0},
+  {"IntrinsicFunctions", "Oi", "", "true", 0},
+  {"OmitFramePointers", "Oy-", "", "false", 0},
+  {"OmitFramePointers", "Oy", "", "true", 0},
+  {"EnableFiberSafeOptimizations", "GT", "", "true", 0},
+  {"WholeProgramOptimization", "GL", "", "true", 0},
+  {"UndefineAllPreprocessorDefinitions", "u", "", "true", 0},
+  {"IgnoreStandardIncludePath", "X", "", "true", 0},
+  {"PreprocessToFile", "P", "", "true", 0},
+  {"PreprocessSuppressLineNumbers", "EP", "", "true", 0},
+  {"PreprocessKeepComments", "C", "", "true", 0},
+  {"StringPooling", "GF-", "", "false", 0},
+  {"StringPooling", "GF", "", "true", 0},
+  {"MinimalRebuild", "Gm-", "", "false", 0},
+  {"MinimalRebuild", "Gm", "", "true", 0},
+  {"SmallerTypeCheck", "RTCc", "", "true", 0},
+  {"FunctionLevelLinking", "Gy-", "", "false", 0},
+  {"FunctionLevelLinking", "Gy", "", "true", 0},
+  {"EnableParallelCodeGeneration", "Qpar-", "", "false", 0},
+  {"EnableParallelCodeGeneration", "Qpar", "", "true", 0},
+  {"FloatingPointExceptions", "fp:except-", "", "false", 0},
+  {"FloatingPointExceptions", "fp:except", "", "true", 0},
+  {"CreateHotpatchableImage", "hotpatch", "", "true", 0},
+  {"DisableLanguageExtensions", "Za", "", "true", 0},
+  {"TreatWChar_tAsBuiltInType", "Zc:wchar_t-", "", "false", 0},
+  {"TreatWChar_tAsBuiltInType", "Zc:wchar_t", "", "true", 0},
+  {"ForceConformanceInForLoopScope", "Zc:forScope-", "", "false", 0},
+  {"ForceConformanceInForLoopScope", "Zc:forScope", "", "true", 0},
+  {"RuntimeTypeInfo", "GR-", "", "false", 0},
+  {"RuntimeTypeInfo", "GR", "", "true", 0},
+  {"OpenMPSupport", "openmp-", "", "false", 0},
+  {"OpenMPSupport", "openmp", "", "true", 0},
+  {"ExpandAttributedSource", "Fx", "", "true", 0},
+  {"UseUnicodeForAssemblerListing", "FAu", "", "true", 0},
+  {"ShowIncludes", "showIncludes", "", "true", 0},
+  {"EnablePREfast", "analyze-", "", "false", 0},
+  {"EnablePREfast", "analyze", "", "true", 0},
+  {"UseFullPaths", "FC", "", "true", 0},
+  {"OmitDefaultLibName", "Zl", "", "true", 0},
+
+  //Bool Properties With Argument
+  {"MultiProcessorCompilation", "MP", "", "true",
+   cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue},
+  {"ProcessorNumber", "MP", "Multi-processor Compilation", "",
+   cmVS7FlagTable::UserValueRequired},
+  {"GenerateXMLDocumentationFiles", "doc", "", "true",
+   cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue},
+  {"XMLDocumentationFileName", "doc", "Generate XML Documentation Files", "",
+   cmVS7FlagTable::UserValueRequired},
+  {"BrowseInformation", "FR", "", "true",
+   cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue},
+  {"BrowseInformationFile", "FR", "Enable Browse Information", "",
+   cmVS7FlagTable::UserValueRequired},
+
+  //String List Properties
+  {"AdditionalIncludeDirectories", "I",
+   "Additional Include Directories",
+   "", cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable},
+  {"AdditionalUsingDirectories", "AI",
+   "Additional #using Directories",
+   "", cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable},
+  {"PreprocessorDefinitions", "D ",
+   "Preprocessor Definitions",
+   "", cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable},
+  {"UndefinePreprocessorDefinitions", "U",
+   "Undefine Preprocessor Definitions",
+   "", cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable},
+  {"DisableSpecificWarnings", "wd",
+   "Disable Specific Warnings",
+   "", cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable},
+  {"ForcedIncludeFiles", "FI",
+   "Forced Include File",
+   "", cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable},
+  {"ForcedUsingFiles", "FU",
+   "Forced #using File",
+   "", cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable},
+  {"PREfastLog", "analyze:log",
+   "Code Analysis Log",
+   "", cmVS7FlagTable::UserFollowing},
+  {"PREfastAdditionalPlugins", "analyze:plugin",
+   "Additional Code Analysis Native plugins",
+   "", cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable},
+  {"TreatSpecificWarningsAsErrors", "we",
+   "Treat Specific Warnings As Errors",
+   "", cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable},
+
+  //String Properties
+  // Skip [TrackerLogDirectory] - no command line Switch.
+  {"PreprocessOutputPath", "Fi",
+   "Preprocess Output Path",
+   "", cmVS7FlagTable::UserValue},
+  {"PrecompiledHeaderFile", "Yc",
+   "Precompiled Header Name",
+   "", cmVS7FlagTable::UserValueRequired},
+  {"PrecompiledHeaderFile", "Yu",
+   "Precompiled Header Name",
+   "", cmVS7FlagTable::UserValueRequired},
+  {"PrecompiledHeaderOutputFile", "Fp",
+   "Precompiled Header Output File",
+   "", cmVS7FlagTable::UserValue},
+  {"AssemblerListingLocation", "Fa",
+   "ASM List Location",
+   "", cmVS7FlagTable::UserValue},
+  {"ObjectFileName", "Fo",
+   "Object File Name",
+   "", cmVS7FlagTable::UserValue},
+  {"ProgramDataBaseFileName", "Fd",
+   "Program Database File Name",
+   "", cmVS7FlagTable::UserValue},
+  // Skip [XMLDocumentationFileName] - no command line Switch.
+  // Skip [BrowseInformationFile] - no command line Switch.
+  // Skip [AdditionalOptions] - no command line Switch.
+  {0,0,0,0,0}
+};
diff --git a/Source/cmVS14LibFlagTable.h b/Source/cmVS14LibFlagTable.h
new file mode 100644
index 0000000..a33f273
--- /dev/null
+++ b/Source/cmVS14LibFlagTable.h
@@ -0,0 +1,102 @@
+static cmVS7FlagTable cmVS14LibFlagTable[] =
+{
+
+  //Enum Properties
+  {"ErrorReporting", "ERRORREPORT:PROMPT",
+   "PromptImmediately", "PromptImmediately", 0},
+  {"ErrorReporting", "ERRORREPORT:QUEUE",
+   "Queue For Next Login", "QueueForNextLogin", 0},
+  {"ErrorReporting", "ERRORREPORT:SEND",
+   "Send Error Report", "SendErrorReport", 0},
+  {"ErrorReporting", "ERRORREPORT:NONE",
+   "No Error Report", "NoErrorReport", 0},
+
+  {"TargetMachine", "MACHINE:ARM",
+   "MachineARM", "MachineARM", 0},
+  {"TargetMachine", "MACHINE:EBC",
+   "MachineEBC", "MachineEBC", 0},
+  {"TargetMachine", "MACHINE:IA64",
+   "MachineIA64", "MachineIA64", 0},
+  {"TargetMachine", "MACHINE:MIPS",
+   "MachineMIPS", "MachineMIPS", 0},
+  {"TargetMachine", "MACHINE:MIPS16",
+   "MachineMIPS16", "MachineMIPS16", 0},
+  {"TargetMachine", "MACHINE:MIPSFPU",
+   "MachineMIPSFPU", "MachineMIPSFPU", 0},
+  {"TargetMachine", "MACHINE:MIPSFPU16",
+   "MachineMIPSFPU16", "MachineMIPSFPU16", 0},
+  {"TargetMachine", "MACHINE:SH4",
+   "MachineSH4", "MachineSH4", 0},
+  {"TargetMachine", "MACHINE:THUMB",
+   "MachineTHUMB", "MachineTHUMB", 0},
+  {"TargetMachine", "MACHINE:X64",
+   "MachineX64", "MachineX64", 0},
+  {"TargetMachine", "MACHINE:X86",
+   "MachineX86", "MachineX86", 0},
+
+  {"SubSystem", "SUBSYSTEM:CONSOLE",
+   "Console", "Console", 0},
+  {"SubSystem", "SUBSYSTEM:WINDOWS",
+   "Windows", "Windows", 0},
+  {"SubSystem", "SUBSYSTEM:NATIVE",
+   "Native", "Native", 0},
+  {"SubSystem", "SUBSYSTEM:EFI_APPLICATION",
+   "EFI Application", "EFI Application", 0},
+  {"SubSystem", "SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER",
+   "EFI Boot Service Driver", "EFI Boot Service Driver", 0},
+  {"SubSystem", "SUBSYSTEM:EFI_ROM",
+   "EFI ROM", "EFI ROM", 0},
+  {"SubSystem", "SUBSYSTEM:EFI_RUNTIME_DRIVER",
+   "EFI Runtime", "EFI Runtime", 0},
+  {"SubSystem", "SUBSYSTEM:WINDOWSCE",
+   "WindowsCE", "WindowsCE", 0},
+  {"SubSystem", "SUBSYSTEM:POSIX",
+   "POSIX", "POSIX", 0},
+
+
+  //Bool Properties
+  {"SuppressStartupBanner", "NOLOGO", "", "true", 0},
+  {"IgnoreAllDefaultLibraries", "NODEFAULTLIB", "", "true", 0},
+  {"TreatLibWarningAsErrors", "WX:NO", "", "false", 0},
+  {"TreatLibWarningAsErrors", "WX", "", "true", 0},
+  {"Verbose", "VERBOSE", "", "true", 0},
+  {"LinkTimeCodeGeneration", "LTCG", "", "true", 0},
+
+  //Bool Properties With Argument
+
+  //String List Properties
+  // Skip [AdditionalDependencies] - no command line Switch.
+  {"AdditionalLibraryDirectories", "LIBPATH:",
+   "Additional Library Directories",
+   "", cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable},
+  {"IgnoreSpecificDefaultLibraries", "NODEFAULTLIB:",
+   "Ignore Specific Default Libraries",
+   "", cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable},
+  {"ExportNamedFunctions", "EXPORT:",
+   "Export Named Functions",
+   "", cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable},
+  {"RemoveObjects", "REMOVE:",
+   "Remove Objects",
+   "", cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable},
+
+  //String Properties
+  {"OutputFile", "OUT:",
+   "Output File",
+   "", cmVS7FlagTable::UserValue},
+  {"ModuleDefinitionFile", "DEF:",
+   "Module Definition File Name",
+   "", cmVS7FlagTable::UserValue},
+  {"ForceSymbolReferences", "INCLUDE:",
+   "Force Symbol References",
+   "", cmVS7FlagTable::UserValue},
+  {"DisplayLibrary", "LIST:",
+   "Display Library to standard output",
+   "", cmVS7FlagTable::UserValue},
+  // Skip [MinimumRequiredVersion] - no command line Switch.
+  {"Name", "NAME:",
+   "Name",
+   "", cmVS7FlagTable::UserValue},
+  // Skip [AdditionalOptions] - no command line Switch.
+  // Skip [TrackerLogDirectory] - no command line Switch.
+  {0,0,0,0,0}
+};
diff --git a/Source/cmVS14LinkFlagTable.h b/Source/cmVS14LinkFlagTable.h
new file mode 100644
index 0000000..6d81d12
--- /dev/null
+++ b/Source/cmVS14LinkFlagTable.h
@@ -0,0 +1,340 @@
+static cmVS7FlagTable cmVS14LinkFlagTable[] =
+{
+
+  //Enum Properties
+  {"ShowProgress", "",
+   "Not Set", "NotSet", 0},
+  {"ShowProgress", "VERBOSE",
+   "Display all progress messages", "LinkVerbose", 0},
+  {"ShowProgress", "VERBOSE:Lib",
+   "For Libraries Searched", "LinkVerboseLib", 0},
+  {"ShowProgress", "VERBOSE:ICF",
+   "About COMDAT folding during optimized linking", "LinkVerboseICF", 0},
+  {"ShowProgress", "VERBOSE:REF",
+   "About data removed during optimized linking", "LinkVerboseREF", 0},
+  {"ShowProgress", "VERBOSE:SAFESEH",
+   "About Modules incompatible with SEH", "LinkVerboseSAFESEH", 0},
+  {"ShowProgress", "VERBOSE:CLR",
+   "About linker activity related to managed code", "LinkVerboseCLR", 0},
+
+  {"ForceFileOutput", "FORCE",
+   "Enabled", "Enabled", 0},
+  {"ForceFileOutput", "FORCE:MULTIPLE",
+   "Multiply Defined Symbol Only", "MultiplyDefinedSymbolOnly", 0},
+  {"ForceFileOutput", "FORCE:UNRESOLVED",
+   "Undefined Symbol Only", "UndefinedSymbolOnly", 0},
+
+  {"CreateHotPatchableImage", "FUNCTIONPADMIN",
+   "Enabled", "Enabled", 0},
+  {"CreateHotPatchableImage", "FUNCTIONPADMIN:5",
+   "X86 Image Only", "X86Image", 0},
+  {"CreateHotPatchableImage", "FUNCTIONPADMIN:6",
+   "X64 Image Only", "X64Image", 0},
+  {"CreateHotPatchableImage", "FUNCTIONPADMIN:16",
+   "Itanium Image Only", "ItaniumImage", 0},
+
+  {"UACExecutionLevel", "level='asInvoker'",
+   "asInvoker", "AsInvoker", 0},
+  {"UACExecutionLevel", "level='highestAvailable'",
+   "highestAvailable", "HighestAvailable", 0},
+  {"UACExecutionLevel", "level='requireAdministrator'",
+   "requireAdministrator", "RequireAdministrator", 0},
+
+  {"SubSystem", "",
+   "Not Set", "NotSet", 0},
+  {"SubSystem", "SUBSYSTEM:CONSOLE",
+   "Console", "Console", 0},
+  {"SubSystem", "SUBSYSTEM:WINDOWS",
+   "Windows", "Windows", 0},
+  {"SubSystem", "SUBSYSTEM:NATIVE",
+   "Native", "Native", 0},
+  {"SubSystem", "SUBSYSTEM:EFI_APPLICATION",
+   "EFI Application", "EFI Application", 0},
+  {"SubSystem", "SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER",
+   "EFI Boot Service Driver", "EFI Boot Service Driver", 0},
+  {"SubSystem", "SUBSYSTEM:EFI_ROM",
+   "EFI ROM", "EFI ROM", 0},
+  {"SubSystem", "SUBSYSTEM:EFI_RUNTIME_DRIVER",
+   "EFI Runtime", "EFI Runtime", 0},
+  {"SubSystem", "SUBSYSTEM:POSIX",
+   "POSIX", "POSIX", 0},
+
+  {"Driver", "",
+   "Not Set", "NotSet", 0},
+  {"Driver", "Driver",
+   "Driver", "Driver", 0},
+  {"Driver", "DRIVER:UPONLY",
+   "UP Only", "UpOnly", 0},
+  {"Driver", "DRIVER:WDM",
+   "WDM", "WDM", 0},
+
+  {"LinkTimeCodeGeneration", "",
+   "Default", "Default", 0},
+  {"LinkTimeCodeGeneration", "LTCG",
+   "Use Link Time Code Generation", "UseLinkTimeCodeGeneration", 0},
+  {"LinkTimeCodeGeneration", "LTCG:PGInstrument",
+   "Profile Guided Optimization - Instrument", "PGInstrument", 0},
+  {"LinkTimeCodeGeneration", "LTCG:PGOptimize",
+   "Profile Guided Optimization - Optimization", "PGOptimization", 0},
+  {"LinkTimeCodeGeneration", "LTCG:PGUpdate",
+   "Profile Guided Optimization - Update", "PGUpdate", 0},
+
+  {"GenerateWindowsMetadata", "WINMD",
+   "Yes", "true", 0},
+  {"GenerateWindowsMetadata", "WINMD:NO",
+   "No", "false", 0},
+
+  {"WindowsMetadataSignHash", "WINMDSIGNHASH:SHA1",
+   "SHA1", "SHA1", 0},
+  {"WindowsMetadataSignHash", "WINMDSIGNHASH:SHA256",
+   "SHA256", "SHA256", 0},
+  {"WindowsMetadataSignHash", "WINMDSIGNHASH:SHA384",
+   "SHA384", "SHA384", 0},
+  {"WindowsMetadataSignHash", "WINMDSIGNHASH:SHA512",
+   "SHA512", "SHA512", 0},
+
+  {"TargetMachine", "",
+   "Not Set", "NotSet", 0},
+  {"TargetMachine", "MACHINE:ARM",
+   "MachineARM", "MachineARM", 0},
+  {"TargetMachine", "MACHINE:EBC",
+   "MachineEBC", "MachineEBC", 0},
+  {"TargetMachine", "MACHINE:IA64",
+   "MachineIA64", "MachineIA64", 0},
+  {"TargetMachine", "MACHINE:MIPS",
+   "MachineMIPS", "MachineMIPS", 0},
+  {"TargetMachine", "MACHINE:MIPS16",
+   "MachineMIPS16", "MachineMIPS16", 0},
+  {"TargetMachine", "MACHINE:MIPSFPU",
+   "MachineMIPSFPU", "MachineMIPSFPU", 0},
+  {"TargetMachine", "MACHINE:MIPSFPU16",
+   "MachineMIPSFPU16", "MachineMIPSFPU16", 0},
+  {"TargetMachine", "MACHINE:SH4",
+   "MachineSH4", "MachineSH4", 0},
+  {"TargetMachine", "MACHINE:THUMB",
+   "MachineTHUMB", "MachineTHUMB", 0},
+  {"TargetMachine", "MACHINE:X64",
+   "MachineX64", "MachineX64", 0},
+  {"TargetMachine", "MACHINE:X86",
+   "MachineX86", "MachineX86", 0},
+
+  {"CLRThreadAttribute", "CLRTHREADATTRIBUTE:MTA",
+   "MTA threading attribute", "MTAThreadingAttribute", 0},
+  {"CLRThreadAttribute", "CLRTHREADATTRIBUTE:STA",
+   "STA threading attribute", "STAThreadingAttribute", 0},
+  {"CLRThreadAttribute", "CLRTHREADATTRIBUTE:NONE",
+   "Default threading attribute", "DefaultThreadingAttribute", 0},
+
+  {"CLRImageType", "CLRIMAGETYPE:IJW",
+   "Force IJW image", "ForceIJWImage", 0},
+  {"CLRImageType", "CLRIMAGETYPE:PURE",
+   "Force Pure IL Image", "ForcePureILImage", 0},
+  {"CLRImageType", "CLRIMAGETYPE:SAFE",
+   "Force Safe IL Image", "ForceSafeILImage", 0},
+  {"CLRImageType", "",
+   "Default image type", "Default", 0},
+
+  {"SignHash", "CLRSIGNHASH:SHA1",
+   "SHA1", "SHA1", 0},
+  {"SignHash", "CLRSIGNHASH:SHA256",
+   "SHA256", "SHA256", 0},
+  {"SignHash", "CLRSIGNHASH:SHA384",
+   "SHA384", "SHA384", 0},
+  {"SignHash", "CLRSIGNHASH:SHA512",
+   "SHA512", "SHA512", 0},
+
+  {"LinkErrorReporting", "ERRORREPORT:PROMPT",
+   "PromptImmediately", "PromptImmediately", 0},
+  {"LinkErrorReporting", "ERRORREPORT:QUEUE",
+   "Queue For Next Login", "QueueForNextLogin", 0},
+  {"LinkErrorReporting", "ERRORREPORT:SEND",
+   "Send Error Report", "SendErrorReport", 0},
+  {"LinkErrorReporting", "ERRORREPORT:NONE",
+   "No Error Report", "NoErrorReport", 0},
+
+  {"CLRSupportLastError", "CLRSupportLastError",
+   "Enabled", "Enabled", 0},
+  {"CLRSupportLastError", "CLRSupportLastError:NO",
+   "Disabled", "Disabled", 0},
+  {"CLRSupportLastError", "CLRSupportLastError:SYSTEMDLL",
+   "System Dlls Only", "SystemDlls", 0},
+
+
+  //Bool Properties
+  {"LinkIncremental", "INCREMENTAL:NO", "", "false", 0},
+  {"LinkIncremental", "INCREMENTAL", "", "true", 0},
+  {"SuppressStartupBanner", "NOLOGO", "", "true", 0},
+  {"LinkStatus", "LTCG:NOSTATUS", "", "false", 0},
+  {"LinkStatus", "LTCG:STATUS", "", "true", 0},
+  {"PreventDllBinding", "ALLOWBIND:NO", "", "false", 0},
+  {"PreventDllBinding", "ALLOWBIND", "", "true", 0},
+  {"TreatLinkerWarningAsErrors", "WX:NO", "", "false", 0},
+  {"TreatLinkerWarningAsErrors", "WX", "", "true", 0},
+  {"IgnoreAllDefaultLibraries", "NODEFAULTLIB", "", "true", 0},
+  {"GenerateManifest", "MANIFEST:NO", "", "false", 0},
+  {"GenerateManifest", "MANIFEST", "", "true", 0},
+  {"AllowIsolation", "ALLOWISOLATION:NO", "", "false", 0},
+  {"UACUIAccess", "uiAccess='false'", "", "false", 0},
+  {"UACUIAccess", "uiAccess='true'", "", "true", 0},
+  {"ManifestEmbed", "manifest:embed", "", "true", 0},
+  {"GenerateDebugInformation", "DEBUG", "", "true", 0},
+  {"MapExports", "MAPINFO:EXPORTS", "", "true", 0},
+  {"AssemblyDebug", "ASSEMBLYDEBUG:DISABLE", "", "false", 0},
+  {"AssemblyDebug", "ASSEMBLYDEBUG", "", "true", 0},
+  {"LargeAddressAware", "LARGEADDRESSAWARE:NO", "", "false", 0},
+  {"LargeAddressAware", "LARGEADDRESSAWARE", "", "true", 0},
+  {"TerminalServerAware", "TSAWARE:NO", "", "false", 0},
+  {"TerminalServerAware", "TSAWARE", "", "true", 0},
+  {"SwapRunFromCD", "SWAPRUN:CD", "", "true", 0},
+  {"SwapRunFromNET", "SWAPRUN:NET", "", "true", 0},
+  {"OptimizeReferences", "OPT:NOREF", "", "false", 0},
+  {"OptimizeReferences", "OPT:REF", "", "true", 0},
+  {"EnableCOMDATFolding", "OPT:NOICF", "", "false", 0},
+  {"EnableCOMDATFolding", "OPT:ICF", "", "true", 0},
+  {"IgnoreEmbeddedIDL", "IGNOREIDL", "", "true", 0},
+  {"AppContainer", "APPCONTAINER", "", "true", 0},
+  {"WindowsMetadataLinkDelaySign", "WINMDDELAYSIGN:NO", "", "false", 0},
+  {"WindowsMetadataLinkDelaySign", "WINMDDELAYSIGN", "", "true", 0},
+  {"NoEntryPoint", "NOENTRY", "", "true", 0},
+  {"SetChecksum", "RELEASE", "", "true", 0},
+  {"RandomizedBaseAddress", "DYNAMICBASE:NO", "", "false", 0},
+  {"RandomizedBaseAddress", "DYNAMICBASE", "", "true", 0},
+  {"FixedBaseAddress", "FIXED:NO", "", "false", 0},
+  {"FixedBaseAddress", "FIXED", "", "true", 0},
+  {"DataExecutionPrevention", "NXCOMPAT:NO", "", "false", 0},
+  {"DataExecutionPrevention", "NXCOMPAT", "", "true", 0},
+  {"TurnOffAssemblyGeneration", "NOASSEMBLY", "", "true", 0},
+  {"SupportUnloadOfDelayLoadedDLL", "DELAY:UNLOAD", "", "true", 0},
+  {"SupportNobindOfDelayLoadedDLL", "DELAY:NOBIND", "", "true", 0},
+  {"Profile", "PROFILE", "", "true", 0},
+  {"LinkDelaySign", "DELAYSIGN:NO", "", "false", 0},
+  {"LinkDelaySign", "DELAYSIGN", "", "true", 0},
+  {"CLRUnmanagedCodeCheck", "CLRUNMANAGEDCODECHECK:NO", "", "false", 0},
+  {"CLRUnmanagedCodeCheck", "CLRUNMANAGEDCODECHECK", "", "true", 0},
+  {"DetectOneDefinitionRule", "ODR", "", "true", 0},
+  {"ImageHasSafeExceptionHandlers", "SAFESEH:NO", "", "false", 0},
+  {"ImageHasSafeExceptionHandlers", "SAFESEH", "", "true", 0},
+  {"LinkDLL", "DLL", "", "true", 0},
+
+  //Bool Properties With Argument
+  {"EnableUAC", "MANIFESTUAC:NO", "", "false", 0},
+  {"EnableUAC", "MANIFESTUAC:", "", "true",
+   cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue},
+  {"UACUIAccess", "MANIFESTUAC:", "Enable User Account Control (UAC)", "",
+   cmVS7FlagTable::UserValueRequired},
+  {"GenerateMapFile", "MAP", "", "true",
+   cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue},
+  {"MapFileName", "MAP:", "Generate Map File", "",
+   cmVS7FlagTable::UserValueRequired},
+
+  //String List Properties
+  {"AdditionalLibraryDirectories", "LIBPATH:",
+   "Additional Library Directories",
+   "", cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable},
+  // Skip [AdditionalDependencies] - no command line Switch.
+  {"IgnoreSpecificDefaultLibraries", "NODEFAULTLIB:",
+   "Ignore Specific Default Libraries",
+   "", cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable},
+  {"AddModuleNamesToAssembly", "ASSEMBLYMODULE:",
+   "Add Module to Assembly",
+   "", cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable},
+  {"EmbedManagedResourceFile", "ASSEMBLYRESOURCE:",
+   "Embed Managed Resource File",
+   "", cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable},
+  {"ForceSymbolReferences", "INCLUDE:",
+   "Force Symbol References",
+   "", cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable},
+  {"DelayLoadDLLs", "DELAYLOAD:",
+   "Delay Loaded Dlls",
+   "", cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable},
+  {"AssemblyLinkResource", "ASSEMBLYLINKRESOURCE:",
+   "Assembly Link Resource",
+   "", cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable},
+  {"AdditionalManifestDependencies", "MANIFESTDEPENDENCY:",
+   "Additional Manifest Dependencies",
+   "", cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable},
+  {"ManifestInput", "manifestinput:",
+   "Manifest Input",
+   "", cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable},
+
+  //String Properties
+  {"OutputFile", "OUT:",
+   "Output File",
+   "", cmVS7FlagTable::UserValue},
+  {"Version", "VERSION:",
+   "Version",
+   "", cmVS7FlagTable::UserValue},
+  {"SpecifySectionAttributes", "SECTION:",
+   "Specify Section Attributes",
+   "", cmVS7FlagTable::UserValue},
+  {"MSDOSStubFileName", "STUB:",
+   "MS-DOS Stub File Name",
+   "", cmVS7FlagTable::UserValue},
+  // Skip [TrackerLogDirectory] - no command line Switch.
+  {"ModuleDefinitionFile", "DEF:",
+   "Module Definition File",
+   "", cmVS7FlagTable::UserValue},
+  {"ManifestFile", "ManifestFile:",
+   "Manifest File",
+   "", cmVS7FlagTable::UserValue},
+  {"ProgramDatabaseFile", "PDB:",
+   "Generate Program Database File",
+   "", cmVS7FlagTable::UserValue},
+  {"StripPrivateSymbols", "PDBSTRIPPED:",
+   "Strip Private Symbols",
+   "", cmVS7FlagTable::UserValue},
+  // Skip [MapFileName] - no command line Switch.
+  // Skip [MinimumRequiredVersion] - no command line Switch.
+  {"HeapReserveSize", "HEAP:",
+   "Heap Reserve Size",
+   "", cmVS7FlagTable::UserValue},
+  // Skip [HeapCommitSize] - no command line Switch.
+  {"StackReserveSize", "STACK:",
+   "Stack Reserve Size",
+   "", cmVS7FlagTable::UserValue},
+  // Skip [StackCommitSize] - no command line Switch.
+  {"FunctionOrder", "ORDER:@",
+   "Function Order",
+   "", cmVS7FlagTable::UserValue},
+  {"ProfileGuidedDatabase", "PGD:",
+   "Profile Guided Database",
+   "", cmVS7FlagTable::UserValue},
+  {"MidlCommandFile", "MIDL:@",
+   "MIDL Commands",
+   "", cmVS7FlagTable::UserValue},
+  {"MergedIDLBaseFileName", "IDLOUT:",
+   "Merged IDL Base File Name",
+   "", cmVS7FlagTable::UserValue},
+  {"TypeLibraryFile", "TLBOUT:",
+   "Type Library",
+   "", cmVS7FlagTable::UserValue},
+  {"WindowsMetadataFile", "WINMDFILE:",
+   "Windows Metadata File",
+   "", cmVS7FlagTable::UserValue},
+  {"WindowsMetadataLinkKeyFile", "WINMDKEYFILE:",
+   "Windows Metadata Key File",
+   "", cmVS7FlagTable::UserValue},
+  {"WindowsMetadataKeyContainer", "WINMDKEYCONTAINER:",
+   "Windows Metadata Key Container",
+   "", cmVS7FlagTable::UserValue},
+  {"EntryPointSymbol", "ENTRY:",
+   "Entry Point",
+   "", cmVS7FlagTable::UserValue},
+  {"BaseAddress", "BASE:",
+   "Base Address",
+   "", cmVS7FlagTable::UserValue},
+  {"ImportLibrary", "IMPLIB:",
+   "Import Library",
+   "", cmVS7FlagTable::UserValue},
+  {"MergeSections", "MERGE:",
+   "Merge Sections",
+   "", cmVS7FlagTable::UserValue},
+  {"LinkKeyFile", "KEYFILE:",
+   "Key File",
+   "", cmVS7FlagTable::UserValue},
+  {"KeyContainer", "KEYCONTAINER:",
+   "Key Container",
+   "", cmVS7FlagTable::UserValue},
+  // Skip [AdditionalOptions] - no command line Switch.
+  {0,0,0,0,0}
+};
diff --git a/Source/cmVS14MASMFlagTable.h b/Source/cmVS14MASMFlagTable.h
new file mode 100644
index 0000000..dce846f
--- /dev/null
+++ b/Source/cmVS14MASMFlagTable.h
@@ -0,0 +1,96 @@
+static cmVS7FlagTable cmVS14MASMFlagTable[] =
+{
+
+  //Enum Properties
+  {"PreserveIdentifierCase", "",
+   "Default", "0", 0},
+  {"PreserveIdentifierCase", "/Cp",
+   "Preserves Identifier Case (/Cp)", "1", 0},
+  {"PreserveIdentifierCase", "/Cu",
+   "Maps all identifiers to upper case. (/Cu)", "2", 0},
+  {"PreserveIdentifierCase", "/Cx",
+   "Preserves case in public and extern symbols. (/Cx)", "3", 0},
+
+  {"WarningLevel", "/W0",
+   "Warning Level 0 (/W0)", "0", 0},
+  {"WarningLevel", "/W1",
+   "Warning Level 1 (/W1)", "1", 0},
+  {"WarningLevel", "/W2",
+   "Warning Level 2 (/W2)", "2", 0},
+  {"WarningLevel", "/W3",
+   "Warning Level 3 (/W3)", "3", 0},
+
+  {"PackAlignmentBoundary", "",
+   "Default", "0", 0},
+  {"PackAlignmentBoundary", "/Zp1",
+   "One Byte Boundary (/Zp1)", "1", 0},
+  {"PackAlignmentBoundary", "/Zp2",
+   "Two Byte Boundary (/Zp2)", "2", 0},
+  {"PackAlignmentBoundary", "/Zp4",
+   "Four Byte Boundary (/Zp4)", "3", 0},
+  {"PackAlignmentBoundary", "/Zp8",
+   "Eight Byte Boundary (/Zp8)", "4", 0},
+  {"PackAlignmentBoundary", "/Zp16",
+   "Sixteen Byte Boundary (/Zp16)", "5", 0},
+
+  {"CallingConvention", "",
+   "Default", "0", 0},
+  {"CallingConvention", "/Gd",
+   "Use C-style Calling Convention (/Gd)", "1", 0},
+  {"CallingConvention", "/Gz",
+   "Use stdcall Calling Convention (/Gz)", "2", 0},
+  {"CallingConvention", "/Gc",
+   "Use Pascal Calling Convention (/Gc)", "3", 0},
+
+  {"ErrorReporting", "/errorReport:prompt",
+   "Prompt to send report immediately (/errorReport:prompt)", "0", 0},
+  {"ErrorReporting", "/errorReport:queue",
+   "Prompt to send report at the next logon (/errorReport:queue)", "1", 0},
+  {"ErrorReporting", "/errorReport:send",
+   "Automatically send report (/errorReport:send)", "2", 0},
+  {"ErrorReporting", "/errorReport:none",
+   "Do not send report (/errorReport:none)", "3", 0},
+
+
+  //Bool Properties
+  {"NoLogo", "/nologo", "", "true", 0},
+  {"GeneratePreprocessedSourceListing", "/EP", "", "true", 0},
+  {"ListAllAvailableInformation", "/Sa", "", "true", 0},
+  {"UseSafeExceptionHandlers", "/safeseh", "", "true", 0},
+  {"AddFirstPassListing", "/Sf", "", "true", 0},
+  {"EnableAssemblyGeneratedCodeListing", "/Sg", "", "true", 0},
+  {"DisableSymbolTable", "/Sn", "", "true", 0},
+  {"EnableFalseConditionalsInListing", "/Sx", "", "true", 0},
+  {"TreatWarningsAsErrors", "/WX", "", "true", 0},
+  {"MakeAllSymbolsPublic", "/Zf", "", "true", 0},
+  {"GenerateDebugInformation", "/Zi", "", "true", 0},
+  {"EnableMASM51Compatibility", "/Zm", "", "true", 0},
+  {"PerformSyntaxCheckOnly", "/Zs", "", "true", 0},
+
+  //Bool Properties With Argument
+
+  //String List Properties
+  {"PreprocessorDefinitions", "/D",
+   "Preprocessor Definitions",
+   "", cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable},
+  {"IncludePaths", "/I",
+   "Include Paths",
+   "", cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable},
+  {"BrowseFile", "/FR",
+   "Generate Browse Information File",
+   "", cmVS7FlagTable::UserValue | cmVS7FlagTable::SemicolonAppendable},
+  // Skip [AdditionalDependencies] - no command line Switch.
+
+  //String Properties
+  // Skip [Inputs] - no command line Switch.
+  {"ObjectFileName", "/Fo",
+   "Object File Name",
+   "", cmVS7FlagTable::UserValue},
+  {"AssembledCodeListingFile", "/Fl",
+   "Assembled Code Listing File",
+   "", cmVS7FlagTable::UserValue},
+  // Skip [CommandLineTemplate] - no command line Switch.
+  // Skip [ExecutionDescription] - no command line Switch.
+  // Skip [AdditionalOptions] - no command line Switch.
+  {0,0,0,0,0}
+};
diff --git a/Source/cmVS14RCFlagTable.h b/Source/cmVS14RCFlagTable.h
new file mode 100644
index 0000000..ebd8d65
--- /dev/null
+++ b/Source/cmVS14RCFlagTable.h
@@ -0,0 +1,7 @@
+static cmVS7FlagTable cmVS14RCFlagTable[] =
+{
+  //Bool Properties
+  {"NullTerminateStrings", "n", "", "true", 0},
+
+  {0,0,0,0,0}
+};
diff --git a/Source/cmVisualStudio10TargetGenerator.cxx b/Source/cmVisualStudio10TargetGenerator.cxx
index 72bb020..26fc317 100644
--- a/Source/cmVisualStudio10TargetGenerator.cxx
+++ b/Source/cmVisualStudio10TargetGenerator.cxx
@@ -21,48 +21,116 @@
 #include "cmLocalVisualStudio7Generator.h"
 #include "cmCustomCommandGenerator.h"
 #include "cmVS10CLFlagTable.h"
+#include "cmVS10RCFlagTable.h"
 #include "cmVS10LinkFlagTable.h"
 #include "cmVS10LibFlagTable.h"
+#include "cmVS10MASMFlagTable.h"
 #include "cmVS11CLFlagTable.h"
+#include "cmVS11RCFlagTable.h"
 #include "cmVS11LinkFlagTable.h"
 #include "cmVS11LibFlagTable.h"
+#include "cmVS11MASMFlagTable.h"
 #include "cmVS12CLFlagTable.h"
+#include "cmVS12RCFlagTable.h"
 #include "cmVS12LinkFlagTable.h"
 #include "cmVS12LibFlagTable.h"
+#include "cmVS12MASMFlagTable.h"
+#include "cmVS14CLFlagTable.h"
+#include "cmVS14RCFlagTable.h"
+#include "cmVS14LinkFlagTable.h"
+#include "cmVS14LibFlagTable.h"
+#include "cmVS14MASMFlagTable.h"
 
 #include <cmsys/auto_ptr.hxx>
 
-static cmVS7FlagTable const*
-cmVSGetCLFlagTable(cmLocalVisualStudioGenerator* lg)
+cmIDEFlagTable const* cmVisualStudio10TargetGenerator::GetClFlagTable() const
 {
-  if(lg->GetVersion() >= cmLocalVisualStudioGenerator::VS12)
-    { return cmVS12CLFlagTable; }
-  else if(lg->GetVersion() == cmLocalVisualStudioGenerator::VS11)
-    { return cmVS11CLFlagTable; }
-  else
-    { return cmVS10CLFlagTable; }
+  if(this->MSTools)
+    {
+    cmLocalVisualStudioGenerator::VSVersion
+      v = this->LocalGenerator->GetVersion();
+    if(v >= cmLocalVisualStudioGenerator::VS14)
+      { return cmVS14CLFlagTable; }
+    else if(v >= cmLocalVisualStudioGenerator::VS12)
+      { return cmVS12CLFlagTable; }
+    else if(v == cmLocalVisualStudioGenerator::VS11)
+      { return cmVS11CLFlagTable; }
+    else
+      { return cmVS10CLFlagTable; }
+    }
+  return 0;
 }
 
-static cmVS7FlagTable const*
-cmVSGetLibFlagTable(cmLocalVisualStudioGenerator* lg)
+cmIDEFlagTable const* cmVisualStudio10TargetGenerator::GetRcFlagTable() const
 {
-  if(lg->GetVersion() >= cmLocalVisualStudioGenerator::VS12)
-    { return cmVS12LibFlagTable; }
-  else if(lg->GetVersion() == cmLocalVisualStudioGenerator::VS11)
-    { return cmVS11LibFlagTable; }
-  else
-    { return cmVS10LibFlagTable; }
+  if(this->MSTools)
+    {
+    cmLocalVisualStudioGenerator::VSVersion
+      v = this->LocalGenerator->GetVersion();
+    if(v >= cmLocalVisualStudioGenerator::VS14)
+      { return cmVS14RCFlagTable; }
+    else if(v >= cmLocalVisualStudioGenerator::VS12)
+      { return cmVS12RCFlagTable; }
+    else if(v == cmLocalVisualStudioGenerator::VS11)
+      { return cmVS11RCFlagTable; }
+    else
+      { return cmVS10RCFlagTable; }
+    }
+  return 0;
 }
 
-static cmVS7FlagTable const*
-cmVSGetLinkFlagTable(cmLocalVisualStudioGenerator* lg)
+cmIDEFlagTable const* cmVisualStudio10TargetGenerator::GetLibFlagTable() const
 {
-  if(lg->GetVersion() >= cmLocalVisualStudioGenerator::VS12)
-    { return cmVS12LinkFlagTable; }
-  else if(lg->GetVersion() == cmLocalVisualStudioGenerator::VS11)
-    { return cmVS11LinkFlagTable; }
-  else
-    { return cmVS10LinkFlagTable; }
+  if(this->MSTools)
+    {
+    cmLocalVisualStudioGenerator::VSVersion
+      v = this->LocalGenerator->GetVersion();
+    if(v >= cmLocalVisualStudioGenerator::VS14)
+      { return cmVS14LibFlagTable; }
+    else if(v >= cmLocalVisualStudioGenerator::VS12)
+      { return cmVS12LibFlagTable; }
+    else if(v == cmLocalVisualStudioGenerator::VS11)
+      { return cmVS11LibFlagTable; }
+    else
+      { return cmVS10LibFlagTable; }
+    }
+  return 0;
+}
+
+cmIDEFlagTable const* cmVisualStudio10TargetGenerator::GetLinkFlagTable() const
+{
+  if(this->MSTools)
+    {
+    cmLocalVisualStudioGenerator::VSVersion
+      v = this->LocalGenerator->GetVersion();
+    if(v >= cmLocalVisualStudioGenerator::VS14)
+      { return cmVS14LinkFlagTable; }
+    else if(v >= cmLocalVisualStudioGenerator::VS12)
+      { return cmVS12LinkFlagTable; }
+    else if(v == cmLocalVisualStudioGenerator::VS11)
+      { return cmVS11LinkFlagTable; }
+    else
+      { return cmVS10LinkFlagTable; }
+    }
+  return 0;
+}
+
+cmIDEFlagTable const* cmVisualStudio10TargetGenerator::GetMasmFlagTable() const
+{
+  if(this->MSTools)
+    {
+    cmLocalVisualStudioGenerator::VSVersion
+      v = this->LocalGenerator->GetVersion();
+    if(v >= cmLocalVisualStudioGenerator::VS14)
+      { return cmVS14MASMFlagTable; }
+    else if(v >= cmLocalVisualStudioGenerator::VS12)
+      { return cmVS12MASMFlagTable; }
+    else if(v == cmLocalVisualStudioGenerator::VS11)
+      { return cmVS11MASMFlagTable; }
+    else
+      { return cmVS10MASMFlagTable; }
+    }
+  return 0;
 }
 
 static std::string cmVS10EscapeXML(std::string arg)
@@ -112,7 +180,22 @@
   this->GlobalGenerator->CreateGUID(this->Name.c_str());
   this->GUID = this->GlobalGenerator->GetGUID(this->Name.c_str());
   this->Platform = gg->GetPlatformName();
+  this->NsightTegra = gg->IsNsightTegra();
+  for(int i =
+        sscanf(gg->GetNsightTegraVersion().c_str(), "%u.%u.%u.%u",
+               &this->NsightTegraVersion[0], &this->NsightTegraVersion[1],
+               &this->NsightTegraVersion[2], &this->NsightTegraVersion[3]);
+      i < 4; ++i)
+    {
+    this->NsightTegraVersion[i] = 0;
+    }
+  this->MSTools = !this->NsightTegra;
+  this->TargetCompileAsWinRT = false;
   this->BuildFileStream = 0;
+  this->IsMissingFiles = false;
+  this->DefaultArtifactDir =
+    this->Makefile->GetStartOutputDirectory() + std::string("/") +
+    this->LocalGenerator->GetTargetDirectory(*this->Target);
 }
 
 cmVisualStudio10TargetGenerator::~cmVisualStudio10TargetGenerator()
@@ -200,6 +283,14 @@
       {
       return;
       }
+    if(!this->ComputeRcOptions())
+      {
+      return;
+      }
+    if(!this->ComputeMasmOptions())
+      {
+      return;
+      }
     if(!this->ComputeLinkOptions())
       {
       return;
@@ -230,11 +321,41 @@
           "xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n");
   this->WriteString(project_defaults.c_str(),0);
 
+  if(this->NsightTegra)
+    {
+    this->WriteString("<PropertyGroup Label=\"NsightTegraProject\">\n", 1);
+    if(this->NsightTegraVersion[0] >= 2)
+      {
+      // Nsight Tegra 2.0 uses project revision 8.
+      this->WriteString("<NsightTegraProjectRevisionNumber>"
+                        "8"
+                        "</NsightTegraProjectRevisionNumber>\n", 2);
+      // Tell newer versions to upgrade silently when loading.
+      this->WriteString("<NsightTegraUpgradeOnceWithoutPrompt>"
+                        "true"
+                        "</NsightTegraUpgradeOnceWithoutPrompt>\n", 2);
+      }
+    else
+      {
+      // Require Nsight Tegra 1.6 for JCompile support.
+      this->WriteString("<NsightTegraProjectRevisionNumber>"
+                        "7"
+                        "</NsightTegraProjectRevisionNumber>\n", 2);
+      }
+    this->WriteString("</PropertyGroup>\n", 1);
+    }
+
   this->WriteProjectConfigurations();
   this->WriteString("<PropertyGroup Label=\"Globals\">\n", 1);
   this->WriteString("<ProjectGUID>", 2);
   (*this->BuildFileStream) <<  "{" << this->GUID << "}</ProjectGUID>\n";
 
+  if(this->MSTools && this->Target->GetType() <= cmTarget::GLOBAL_TARGET)
+    {
+    this->WriteApplicationTypeSettings();
+    this->VerifyNecessaryFiles();
+    }
+
   const char* vsProjectTypes =
     this->Target->GetProperty("VS_GLOBAL_PROJECT_TYPES");
   if(vsProjectTypes)
@@ -269,6 +390,11 @@
       }
     }
 
+  if(this->Target->GetPropertyAsBool("VS_WINRT_COMPONENT"))
+    {
+    this->WriteString("<WinMDAssembly>true</WinMDAssembly>\n", 2);
+    }
+
   const char* vsGlobalKeyword =
     this->Target->GetProperty("VS_GLOBAL_KEYWORD");
   if(!vsGlobalKeyword)
@@ -292,19 +418,20 @@
     }
 
   this->WriteString("<Platform>", 2);
-  (*this->BuildFileStream) << this->Platform << "</Platform>\n";
+  (*this->BuildFileStream) << cmVS10EscapeXML(this->Platform)
+                           << "</Platform>\n";
   const char* projLabel = this->Target->GetProperty("PROJECT_LABEL");
   if(!projLabel)
     {
     projLabel = this->Name.c_str();
     }
   this->WriteString("<ProjectName>", 2);
-  (*this->BuildFileStream) << projLabel << "</ProjectName>\n";
+  (*this->BuildFileStream) << cmVS10EscapeXML(projLabel) << "</ProjectName>\n";
   if(const char* targetFrameworkVersion = this->Target->GetProperty(
        "VS_DOTNET_TARGET_FRAMEWORK_VERSION"))
     {
     this->WriteString("<TargetFrameworkVersion>", 2);
-    (*this->BuildFileStream) << targetFrameworkVersion
+    (*this->BuildFileStream) << cmVS10EscapeXML(targetFrameworkVersion)
                              << "</TargetFrameworkVersion>\n";
     }
   this->WriteString("</PropertyGroup>\n", 1);
@@ -324,9 +451,10 @@
   this->WriteString("<ImportGroup Label=\"PropertySheets\">\n", 1);
   this->WriteString("<Import Project=\"" VS10_USER_PROPS "\""
                     " Condition=\"exists('" VS10_USER_PROPS "')\""
-                    " Label=\"LocalAppDataPlatform\" />", 2);
+                    " Label=\"LocalAppDataPlatform\" />\n", 2);
   this->WriteString("</ImportGroup>\n", 1);
   this->WriteString("<PropertyGroup Label=\"UserMacros\" />\n", 1);
+  this->WriteWinRTPackageCertificateKeyFile();
   this->WritePathAndIncrementalLinkOptions();
   this->WriteItemDefinitionGroups();
   this->WriteCustomCommands();
@@ -338,6 +466,7 @@
   this->WriteString(
     "<Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.targets\""
     " />\n", 1);
+  this->WriteTargetSpecificReferences();
   this->WriteString("<ImportGroup Label=\"ExtensionTargets\">\n", 1);
   if (this->GlobalGenerator->IsMasmEnabled())
     {
@@ -417,6 +546,22 @@
     }
 }
 
+void cmVisualStudio10TargetGenerator::WriteTargetSpecificReferences()
+{
+  if(this->MSTools)
+    {
+    if(this->GlobalGenerator->TargetsWindowsPhone() &&
+       this->GlobalGenerator->GetSystemVersion() == "8.0")
+      {
+      this->WriteString(
+        "<Import Project=\""
+        "$(MSBuildExtensionsPath)\\Microsoft\\WindowsPhone\\v"
+        "$(TargetPlatformVersion)\\Microsoft.Cpp.WindowsPhone."
+        "$(TargetPlatformVersion).targets\" />\n", 1);
+      }
+    }
+}
+
 void cmVisualStudio10TargetGenerator::WriteWinRTReferences()
 {
   std::vector<std::string> references;
@@ -425,6 +570,13 @@
     {
     cmSystemTools::ExpandListArgument(vsWinRTReferences, references);
     }
+
+  if(this->GlobalGenerator->TargetsWindowsPhone() &&
+     this->GlobalGenerator->GetSystemVersion() == "8.0" &&
+     references.empty())
+    {
+    references.push_back("platform.winmd");
+    }
   if(!references.empty())
     {
     this->WriteString("<ItemGroup>\n", 1);
@@ -456,7 +608,8 @@
     this->WriteString("<Configuration>", 3);
     (*this->BuildFileStream ) <<  *i << "</Configuration>\n";
     this->WriteString("<Platform>", 3);
-    (*this->BuildFileStream) << this->Platform << "</Platform>\n";
+    (*this->BuildFileStream) << cmVS10EscapeXML(this->Platform)
+                             << "</Platform>\n";
     this->WriteString("</ProjectConfiguration>\n", 2);
     }
   this->WriteString("</ItemGroup>\n", 1);
@@ -464,8 +617,6 @@
 
 void cmVisualStudio10TargetGenerator::WriteProjectConfigurationValues()
 {
-  cmGlobalVisualStudio10Generator* gg =
-    static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator);
   std::vector<std::string> *configs =
     static_cast<cmGlobalVisualStudio7Generator *>
     (this->GlobalGenerator)->GetConfigurations();
@@ -487,12 +638,29 @@
         configType += "StaticLibrary";
         break;
       case cmTarget::EXECUTABLE:
-        configType += "Application";
+        if(this->NsightTegra &&
+           !this->Target->GetPropertyAsBool("ANDROID_GUI"))
+          {
+          // Android executables are .so too.
+          configType += "DynamicLibrary";
+          }
+        else
+          {
+          configType += "Application";
+          }
         break;
       case cmTarget::UTILITY:
-        configType += "Utility";
-        break;
       case cmTarget::GLOBAL_TARGET:
+        if(this->NsightTegra)
+          {
+          // Tegra-Android platform does not understand "Utility".
+          configType += "StaticLibrary";
+          }
+        else
+          {
+          configType += "Utility";
+          }
+        break;
       case cmTarget::UNKNOWN_LIBRARY:
       case cmTarget::INTERFACE_LIBRARY:
         break;
@@ -500,55 +668,94 @@
     configType += "</ConfigurationType>\n";
     this->WriteString(configType.c_str(), 2);
 
-    const char* mfcFlag =
-      this->Target->GetMakefile()->GetDefinition("CMAKE_MFC_FLAG");
-    std::string mfcFlagValue = mfcFlag ? mfcFlag : "0";
-
-    std::string useOfMfcValue = "false";
-    if(mfcFlagValue == "1")
+    if(this->MSTools)
       {
-      useOfMfcValue = "Static";
+      this->WriteMSToolConfigurationValues(*i);
       }
-    else if(mfcFlagValue == "2")
+    else if(this->NsightTegra)
       {
-      useOfMfcValue = "Dynamic";
-      }
-    std::string mfcLine = "<UseOfMfc>";
-    mfcLine += useOfMfcValue + "</UseOfMfc>\n";
-    this->WriteString(mfcLine.c_str(), 2);
-
-    if((this->Target->GetType() <= cmTarget::OBJECT_LIBRARY &&
-       this->ClOptions[*i]->UsingUnicode()) ||
-       this->Target->GetPropertyAsBool("VS_WINRT_EXTENSIONS"))
-      {
-      this->WriteString("<CharacterSet>Unicode</CharacterSet>\n", 2);
-      }
-    else if (this->Target->GetType() <= cmTarget::MODULE_LIBRARY &&
-       this->ClOptions[*i]->UsingSBCS())
-      {
-      this->WriteString("<CharacterSet>NotSet</CharacterSet>\n", 2);
-      }
-    else
-      {
-      this->WriteString("<CharacterSet>MultiByte</CharacterSet>\n", 2);
-      }
-    if(const char* toolset = gg->GetPlatformToolset())
-      {
-      std::string pts = "<PlatformToolset>";
-      pts += toolset;
-      pts += "</PlatformToolset>\n";
-      this->WriteString(pts.c_str(), 2);
-      }
-    if(this->Target->GetPropertyAsBool("VS_WINRT_EXTENSIONS"))
-      {
-      this->WriteString("<WindowsAppContainer>true"
-                        "</WindowsAppContainer>\n", 2);
+      this->WriteNsightTegraConfigurationValues(*i);
       }
 
     this->WriteString("</PropertyGroup>\n", 1);
     }
 }
 
+//----------------------------------------------------------------------------
+void cmVisualStudio10TargetGenerator
+::WriteMSToolConfigurationValues(std::string const& config)
+{
+  cmGlobalVisualStudio10Generator* gg =
+    static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator);
+  const char* mfcFlag =
+    this->Target->GetMakefile()->GetDefinition("CMAKE_MFC_FLAG");
+  std::string mfcFlagValue = mfcFlag ? mfcFlag : "0";
+
+  std::string useOfMfcValue = "false";
+  if(mfcFlagValue == "1")
+    {
+    useOfMfcValue = "Static";
+    }
+  else if(mfcFlagValue == "2")
+    {
+    useOfMfcValue = "Dynamic";
+    }
+  std::string mfcLine = "<UseOfMfc>";
+  mfcLine += useOfMfcValue + "</UseOfMfc>\n";
+  this->WriteString(mfcLine.c_str(), 2);
+
+  if((this->Target->GetType() <= cmTarget::OBJECT_LIBRARY &&
+      this->ClOptions[config]->UsingUnicode()) ||
+     this->Target->GetPropertyAsBool("VS_WINRT_COMPONENT") ||
+     this->GlobalGenerator->TargetsWindowsPhone() ||
+     this->GlobalGenerator->TargetsWindowsStore() ||
+     this->Target->GetPropertyAsBool("VS_WINRT_EXTENSIONS"))
+    {
+    this->WriteString("<CharacterSet>Unicode</CharacterSet>\n", 2);
+    }
+  else if (this->Target->GetType() <= cmTarget::MODULE_LIBRARY &&
+           this->ClOptions[config]->UsingSBCS())
+    {
+    this->WriteString("<CharacterSet>NotSet</CharacterSet>\n", 2);
+    }
+  else
+    {
+    this->WriteString("<CharacterSet>MultiByte</CharacterSet>\n", 2);
+    }
+  if(const char* toolset = gg->GetPlatformToolset())
+    {
+    std::string pts = "<PlatformToolset>";
+    pts += toolset;
+    pts += "</PlatformToolset>\n";
+    this->WriteString(pts.c_str(), 2);
+    }
+  if(this->Target->GetPropertyAsBool("VS_WINRT_COMPONENT") ||
+     this->Target->GetPropertyAsBool("VS_WINRT_EXTENSIONS"))
+    {
+    this->WriteString("<WindowsAppContainer>true"
+                      "</WindowsAppContainer>\n", 2);
+    }
+}
+
+//----------------------------------------------------------------------------
+void cmVisualStudio10TargetGenerator
+::WriteNsightTegraConfigurationValues(std::string const&)
+{
+  cmGlobalVisualStudio10Generator* gg =
+    static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator);
+  const char* toolset = gg->GetPlatformToolset();
+  std::string ntv = "<NdkToolchainVersion>";
+  ntv += toolset? toolset : "Default";
+  ntv += "</NdkToolchainVersion>\n";
+  this->WriteString(ntv.c_str(), 2);
+  if(const char* api = this->Target->GetProperty("ANDROID_API"))
+    {
+    this->WriteString("<AndroidTargetAPI>", 2);
+    (*this->BuildFileStream ) <<
+      "android-" << cmVS10EscapeXML(api) << "</AndroidTargetAPI>\n";
+    }
+}
+
 void cmVisualStudio10TargetGenerator::WriteCustomCommands()
 {
   this->SourcesVisited.clear();
@@ -639,7 +846,7 @@
     (*this->BuildFileStream ) << script << "</Command>\n";
     this->WritePlatformConfigTag("AdditionalInputs", i->c_str(), 3);
 
-    (*this->BuildFileStream ) << source->GetFullPath();
+    (*this->BuildFileStream ) << cmVS10EscapeXML(source->GetFullPath());
     for(std::vector<std::string>::const_iterator d =
           ccg.GetDepends().begin();
         d != ccg.GetDepends().end();
@@ -649,7 +856,7 @@
       if(this->LocalGenerator->GetRealDependency(d->c_str(), i->c_str(), dep))
         {
         this->ConvertToWindowsSlash(dep);
-        (*this->BuildFileStream ) << ";" << dep;
+        (*this->BuildFileStream ) << ";" << cmVS10EscapeXML(dep);
         }
       }
     (*this->BuildFileStream ) << ";%(AdditionalInputs)</AdditionalInputs>\n";
@@ -662,7 +869,7 @@
       {
       std::string out = *o;
       this->ConvertToWindowsSlash(out);
-      (*this->BuildFileStream ) << sep << out;
+      (*this->BuildFileStream ) << sep << cmVS10EscapeXML(out);
       sep = ";";
       }
     (*this->BuildFileStream ) << "</Outputs>\n";
@@ -752,6 +959,49 @@
     this->WriteGroupSources(ti->first.c_str(), ti->second, sourceGroups);
     }
 
+  // Added files are images and the manifest.
+  if (!this->AddedFiles.empty())
+    {
+    this->WriteString("<ItemGroup>\n", 1);
+    for(std::vector<std::string>::const_iterator
+          oi = this->AddedFiles.begin(); oi != this->AddedFiles.end(); ++oi)
+      {
+      std::string fileName = cmSystemTools::LowerCase(
+        cmSystemTools::GetFilenameName(*oi));
+      if (fileName == "wmappmanifest.xml")
+        {
+        this->WriteString("<XML Include=\"", 2);
+        (*this->BuildFileStream) << *oi << "\">\n";
+        this->WriteString("<Filter>Resource Files</Filter>\n", 3);
+        this->WriteString("</XML>\n", 2);
+        }
+      else if(cmSystemTools::GetFilenameExtension(fileName) ==
+              ".appxmanifest")
+        {
+        this->WriteString("<AppxManifest Include=\"", 2);
+        (*this->BuildFileStream) << *oi << "\">\n";
+        this->WriteString("<Filter>Resource Files</Filter>\n", 3);
+        this->WriteString("</AppxManifest>\n", 2);
+        }
+      else if(cmSystemTools::GetFilenameExtension(fileName) ==
+              ".pfx")
+        {
+        this->WriteString("<None Include=\"", 2);
+        (*this->BuildFileStream) << *oi << "\">\n";
+        this->WriteString("<Filter>Resource Files</Filter>\n", 3);
+        this->WriteString("</None>\n", 2);
+        }
+      else
+        {
+        this->WriteString("<Image Include=\"", 2);
+        (*this->BuildFileStream) << *oi << "\">\n";
+        this->WriteString("<Filter>Resource Files</Filter>\n", 3);
+        this->WriteString("</Image>\n", 2);
+        }
+      }
+    this->WriteString("</ItemGroup>\n", 1);
+    }
+
   std::vector<cmSourceFile const*> resxObjs;
     this->GeneratorTarget->GetResxSources(resxObjs, "");
   if(!resxObjs.empty())
@@ -763,7 +1013,7 @@
       std::string obj = (*oi)->GetFullPath();
       this->WriteString("<EmbeddedResource Include=\"", 2);
       this->ConvertToWindowsSlash(obj);
-      (*this->BuildFileStream ) << obj << "\">\n";
+      (*this->BuildFileStream ) << cmVS10EscapeXML(obj) << "\">\n";
       this->WriteString("<Filter>Resource Files</Filter>\n", 3);
       this->WriteString("</EmbeddedResource>\n", 2);
       }
@@ -782,7 +1032,7 @@
       std::string obj = *oi;
       this->WriteString("<Object Include=\"", 2);
       this->ConvertToWindowsSlash(obj);
-      (*this->BuildFileStream ) << obj << "\">\n";
+      (*this->BuildFileStream ) << cmVS10EscapeXML(obj) << "\">\n";
       this->WriteString("<Filter>Object Libraries</Filter>\n", 3);
       this->WriteString("</Object>\n", 2);
       }
@@ -825,7 +1075,7 @@
     this->WriteString("</Filter>\n", 2);
     }
 
-  if(!resxObjs.empty())
+  if(!resxObjs.empty() || !this->AddedFiles.empty())
     {
     this->WriteString("<Filter Include=\"Resource Files\">\n", 2);
     std::string guidName = "SG_Filter_Resource Files";
@@ -917,7 +1167,7 @@
     std::string path = this->ConvertPath(source, s->RelativePath);
     this->ConvertToWindowsSlash(path);
     (*this->BuildFileStream) << name << " Include=\""
-                             << path;
+                             << cmVS10EscapeXML(path);
     if(strlen(filter))
       {
       (*this->BuildFileStream) << "\">\n";
@@ -934,8 +1184,129 @@
   this->WriteString("</ItemGroup>\n", 1);
 }
 
+void cmVisualStudio10TargetGenerator::WriteHeaderSource(cmSourceFile const* sf)
+{
+  if(this->IsResxHeader(sf->GetFullPath()))
+    {
+    this->WriteSource("ClInclude", sf, ">\n");
+    this->WriteString("<FileType>CppForm</FileType>\n", 3);
+    this->WriteString("</ClInclude>\n", 2);
+    }
+  else
+    {
+    this->WriteSource("ClInclude", sf);
+    }
+}
+
+void cmVisualStudio10TargetGenerator::WriteExtraSource(cmSourceFile const* sf)
+{
+  bool toolHasSettings = false;
+  std::string tool = "None";
+  std::string shaderType;
+  std::string ext = cmSystemTools::LowerCase(sf->GetExtension());
+  if(ext == "hlsl")
+    {
+    tool = "FXCompile";
+    // Figure out the type of shader compiler to use.
+    if(const char* st = sf->GetProperty("VS_SHADER_TYPE"))
+      {
+      shaderType = st;
+      toolHasSettings = true;
+      }
+    }
+  else if(ext == "jpg" ||
+          ext == "png")
+    {
+    tool = "Image";
+    }
+  else if(ext == "xml")
+    {
+    tool = "XML";
+    }
+  if(this->NsightTegra)
+    {
+    // Nsight Tegra needs specific file types to check up-to-dateness.
+    std::string name =
+      cmSystemTools::LowerCase(sf->GetLocation().GetName());
+    if(name == "androidmanifest.xml" ||
+       name == "build.xml" ||
+       name == "proguard.cfg" ||
+       name == "proguard-project.txt" ||
+       ext == "properties")
+      {
+      tool = "AndroidBuild";
+      }
+    else if(ext == "java")
+      {
+      tool = "JCompile";
+      }
+    else if(ext == "asm" || ext == "s")
+      {
+      tool = "ClCompile";
+      }
+    }
+
+  std::string deployContent;
+  if(this->GlobalGenerator->TargetsWindowsPhone() ||
+     this->GlobalGenerator->TargetsWindowsStore())
+    {
+    const char* content = sf->GetProperty("VS_DEPLOYMENT_CONTENT");
+    if(content && *content)
+      {
+      toolHasSettings = true;
+      deployContent = content;
+      }
+    }
+
+  if(toolHasSettings)
+    {
+    this->WriteSource(tool, sf, ">\n");
+
+    if(!deployContent.empty())
+      {
+      std::vector<std::string> const* configs =
+        this->GlobalGenerator->GetConfigurations();
+      cmGeneratorExpression ge;
+      cmsys::auto_ptr<cmCompiledGeneratorExpression> cge =
+        ge.Parse(deployContent);
+      for(size_t i = 0; i != configs->size(); ++i)
+        {
+        if(0 == strcmp(cge->Evaluate(this->Makefile, (*configs)[i]), "1"))
+          {
+          this->WriteString("<DeploymentContent Condition=\""
+                            "'$(Configuration)|$(Platform)'=='", 3);
+          (*this->BuildFileStream) << (*configs)[i] << "|"
+                                   << this->Platform << "'\">true";
+          this->WriteString("</DeploymentContent>\n", 0);
+          }
+        else
+          {
+          this->WriteString("<ExcludedFromBuild Condition=\""
+                            "'$(Configuration)|$(Platform)'=='", 3);
+          (*this->BuildFileStream) << (*configs)[i] << "|"
+                                   << this->Platform << "'\">true";
+          this->WriteString("</ExcludedFromBuild>\n", 0);
+          }
+        }
+      }
+    if(!shaderType.empty())
+      {
+      this->WriteString("<ShaderType>", 3);
+      (*this->BuildFileStream) << cmVS10EscapeXML(shaderType)
+                               << "</ShaderType>\n";
+      }
+
+    this->WriteString("</", 2);
+    (*this->BuildFileStream) << tool << ">\n";
+    }
+  else
+    {
+    this->WriteSource(tool, sf);
+    }
+}
+
 void cmVisualStudio10TargetGenerator::WriteSource(
-  const char* tool, cmSourceFile const* sf, const char* end)
+  std::string const& tool, cmSourceFile const* sf, const char* end)
 {
   // Visual Studio tools append relative paths to the current dir, as in:
   //
@@ -972,26 +1343,16 @@
     }
   this->ConvertToWindowsSlash(sourceFile);
   this->WriteString("<", 2);
-  (*this->BuildFileStream ) << tool << " Include=\"" << sourceFile << "\"";
-
-  if(sf->GetExtension() == "h" &&
-    this->IsResxHeader(sf->GetFullPath()))
-    {
-      (*this->BuildFileStream ) << ">\n";
-      this->WriteString("<FileType>CppForm</FileType>\n", 3);
-      this->WriteString("</ClInclude>\n", 2);
-    }
-  else
-    {
-      (*this->BuildFileStream ) << (end? end : " />\n");
-    }
+  (*this->BuildFileStream ) << tool << " Include=\""
+                            << cmVS10EscapeXML(sourceFile) << "\""
+                            << (end? end : " />\n");
 
   ToolSource toolSource = {sf, forceRelative};
   this->Tools[tool].push_back(toolSource);
 }
 
 void cmVisualStudio10TargetGenerator::WriteSources(
-  const char* tool, std::vector<cmSourceFile const*> const& sources)
+  std::string const& tool, std::vector<cmSourceFile const*> const& sources)
 {
   for(std::vector<cmSourceFile const*>::const_iterator
         si = sources.begin(); si != sources.end(); ++si)
@@ -1010,7 +1371,11 @@
 
   std::vector<cmSourceFile const*> headerSources;
   this->GeneratorTarget->GetHeaderSources(headerSources, "");
-  this->WriteSources("ClInclude", headerSources);
+  for(std::vector<cmSourceFile const*>::const_iterator
+        si = headerSources.begin(); si != headerSources.end(); ++si)
+    {
+    this->WriteHeaderSource(*si);
+    }
   std::vector<cmSourceFile const*> idlSources;
   this->GeneratorTarget->GetIDLSources(idlSources, "");
   this->WriteSources("Midl", idlSources);
@@ -1022,12 +1387,12 @@
       si != objectSources.end(); ++si)
     {
     const std::string& lang = (*si)->GetLanguage();
-    const char* tool = NULL;
+    std::string tool;
     if (lang == "C"|| lang == "CXX")
       {
       tool = "ClCompile";
       }
-    else if (lang == "ASM_NASM" &&
+    else if (lang == "ASM_MASM" &&
              this->GlobalGenerator->IsMasmEnabled())
       {
       tool = "MASM";
@@ -1037,7 +1402,7 @@
       tool = "ResourceCompile";
       }
 
-    if (tool)
+    if (!tool.empty())
       {
       this->WriteSource(tool, *si, " ");
       if (this->OutputSourceSpecificFlags(*si))
@@ -1056,6 +1421,14 @@
       }
     }
 
+  std::vector<cmSourceFile const*> manifestSources;
+  this->GeneratorTarget->GetAppManifest(manifestSources, "");
+  this->WriteSources("AppxManifest", manifestSources);
+
+  std::vector<cmSourceFile const*> certificateSources;
+  this->GeneratorTarget->GetCertificates(certificateSources, "");
+  this->WriteSources("None", certificateSources);
+
   std::vector<cmSourceFile const*> externalObjects;
   this->GeneratorTarget->GetExternalObjects(externalObjects, "");
   for(std::vector<cmSourceFile const*>::iterator
@@ -1093,7 +1466,11 @@
 
   std::vector<cmSourceFile const*> extraSources;
   this->GeneratorTarget->GetExtraSources(extraSources, "");
-  this->WriteSources("None", extraSources);
+  for(std::vector<cmSourceFile const*>::const_iterator
+        si = extraSources.begin(); si != extraSources.end(); ++si)
+    {
+    this->WriteExtraSource(*si);
+    }
 
   // Add object library contents as external objects.
   std::vector<std::string> objs;
@@ -1104,7 +1481,12 @@
     std::string obj = *oi;
     this->WriteString("<Object Include=\"", 2);
     this->ConvertToWindowsSlash(obj);
-    (*this->BuildFileStream ) << obj << "\" />\n";
+    (*this->BuildFileStream ) << cmVS10EscapeXML(obj) << "\" />\n";
+    }
+
+  if (this->IsMissingFiles)
+    {
+    this->WriteMissingFiles();
     }
 
   this->WriteString("</ItemGroup>\n", 1);
@@ -1144,19 +1526,21 @@
     }
   // if the source file does not match the linker language
   // then force c or c++
+  const char* compileAs = 0;
   if(needForceLang || (linkLanguage != lang))
     {
     if(lang == "CXX")
       {
       // force a C++ file type
-      flags += " /TP ";
+      compileAs = "CompileAsCpp";
       }
     else if(lang == "C")
       {
       // force to c
-      flags += " /TC ";
+      compileAs = "CompileAsC";
       }
     }
+  bool noWinRT = this->TargetCompileAsWinRT && lang == "C";
   bool hasFlags = false;
   // for the first time we need a new line if there is something
   // produced here.
@@ -1190,7 +1574,7 @@
       }
     // if we have flags or defines for this config then
     // use them
-    if(flags.size() || configDefines.size())
+    if(!flags.empty() || !configDefines.empty() || compileAs || noWinRT)
       {
       (*this->BuildFileStream ) << firstString;
       firstString = ""; // only do firstString once
@@ -1198,8 +1582,21 @@
       cmVisualStudioGeneratorOptions
         clOptions(this->LocalGenerator,
                   cmVisualStudioGeneratorOptions::Compiler,
-                  cmVSGetCLFlagTable(this->LocalGenerator), 0, this);
+                  this->GetClFlagTable(), 0, this);
+      if(compileAs)
+        {
+        clOptions.AddFlag("CompileAs", compileAs);
+        }
+      if(noWinRT)
+        {
+        clOptions.AddFlag("CompileAsWinRT", "false");
+        }
       clOptions.Parse(flags.c_str());
+      if(clOptions.HasFlag("AdditionalIncludeDirectories"))
+        {
+        clOptions.AppendFlag("AdditionalIncludeDirectories",
+                             "%(AdditionalIncludeDirectories)");
+        }
       clOptions.AddDefines(configDefines.c_str());
       clOptions.SetConfiguration((*config).c_str());
       clOptions.OutputAdditionalOptions(*this->BuildFileStream, "      ", "");
@@ -1260,23 +1657,28 @@
       this->ConvertToWindowsSlash(outDir);
 
       this->WritePlatformConfigTag("OutDir", config->c_str(), 3);
-      *this->BuildFileStream << outDir
+      *this->BuildFileStream << cmVS10EscapeXML(outDir)
                              << "</OutDir>\n";
 
       this->WritePlatformConfigTag("IntDir", config->c_str(), 3);
-      *this->BuildFileStream << intermediateDir
+      *this->BuildFileStream << cmVS10EscapeXML(intermediateDir)
                              << "</IntDir>\n";
 
+      std::string name =
+        cmSystemTools::GetFilenameWithoutLastExtension(targetNameFull);
       this->WritePlatformConfigTag("TargetName", config->c_str(), 3);
-      *this->BuildFileStream
-        << cmSystemTools::GetFilenameWithoutLastExtension(
-             targetNameFull.c_str())
-        << "</TargetName>\n";
+      *this->BuildFileStream << cmVS10EscapeXML(name) << "</TargetName>\n";
 
+      std::string ext =
+        cmSystemTools::GetFilenameLastExtension(targetNameFull);
+      if(ext.empty())
+        {
+        // An empty TargetExt causes a default extension to be used.
+        // A single "." appears to be treated as an empty extension.
+        ext = ".";
+        }
       this->WritePlatformConfigTag("TargetExt", config->c_str(), 3);
-      *this->BuildFileStream
-        << cmSystemTools::GetFilenameLastExtension(targetNameFull.c_str())
-        << "</TargetExt>\n";
+      *this->BuildFileStream << cmVS10EscapeXML(ext) << "</TargetExt>\n";
 
       this->OutputLinkIncremental(*config);
       }
@@ -1290,6 +1692,10 @@
 cmVisualStudio10TargetGenerator::
 OutputLinkIncremental(std::string const& configName)
 {
+  if(!this->MSTools)
+    {
+    return;
+    }
   // static libraries and things greater than modules do not need
   // to set this option
   if(this->Target->GetType() == cmTarget::STATIC_LIBRARY
@@ -1355,62 +1761,64 @@
 
   cmsys::auto_ptr<Options> pOptions(
     new Options(this->LocalGenerator, Options::Compiler,
-                cmVSGetCLFlagTable(this->LocalGenerator)));
+                this->GetClFlagTable()));
   Options& clOptions = *pOptions;
 
   std::string flags;
-  // collect up flags for
-  if(this->Target->GetType() < cmTarget::UTILITY)
+  const std::string& linkLanguage =
+    this->Target->GetLinkerLanguage(configName.c_str());
+  if(linkLanguage.empty())
     {
-    const std::string& linkLanguage =
-      this->Target->GetLinkerLanguage(configName.c_str());
-    if(linkLanguage.empty())
-      {
-      cmSystemTools::Error
-        ("CMake can not determine linker language for target: ",
-         this->Name.c_str());
-      return false;
-      }
-    if(linkLanguage == "C" || linkLanguage == "CXX"
-       || linkLanguage == "Fortran")
-      {
-      std::string baseFlagVar = "CMAKE_";
-      baseFlagVar += linkLanguage;
-      baseFlagVar += "_FLAGS";
-      flags = this->
-        Target->GetMakefile()->GetRequiredDefinition(baseFlagVar.c_str());
-      std::string flagVar = baseFlagVar + std::string("_") +
-        cmSystemTools::UpperCase(configName);
-      flags += " ";
-      flags += this->
-        Target->GetMakefile()->GetRequiredDefinition(flagVar.c_str());
-      }
-    // set the correct language
-    if(linkLanguage == "C")
-      {
-      flags += " /TC ";
-      }
-    if(linkLanguage == "CXX")
-      {
-      flags += " /TP ";
-      }
-    this->LocalGenerator->AddCompileOptions(flags, this->Target,
-                                            linkLanguage, configName.c_str());
+    cmSystemTools::Error
+      ("CMake can not determine linker language for target: ",
+       this->Name.c_str());
+    return false;
     }
+  if(linkLanguage == "C" || linkLanguage == "CXX"
+     || linkLanguage == "Fortran")
+    {
+    std::string baseFlagVar = "CMAKE_";
+    baseFlagVar += linkLanguage;
+    baseFlagVar += "_FLAGS";
+    flags = this->
+      Target->GetMakefile()->GetRequiredDefinition(baseFlagVar.c_str());
+    std::string flagVar = baseFlagVar + std::string("_") +
+      cmSystemTools::UpperCase(configName);
+    flags += " ";
+    flags += this->
+      Target->GetMakefile()->GetRequiredDefinition(flagVar.c_str());
+    }
+  // set the correct language
+  if(linkLanguage == "C")
+    {
+    clOptions.AddFlag("CompileAs", "CompileAsC");
+    }
+  if(linkLanguage == "CXX")
+    {
+    clOptions.AddFlag("CompileAs", "CompileAsCpp");
+    }
+  this->LocalGenerator->AddCompileOptions(flags, this->Target,
+                                          linkLanguage, configName.c_str());
 
   // Get preprocessor definitions for this directory.
   std::string defineFlags = this->Target->GetMakefile()->GetDefineFlags();
-  clOptions.FixExceptionHandlingDefault();
-  clOptions.AddFlag("PrecompiledHeader", "NotUsing");
-  std::string asmLocation = configName + "/";
-  clOptions.AddFlag("AssemblerListingLocation", asmLocation.c_str());
+  if(this->MSTools)
+    {
+    clOptions.FixExceptionHandlingDefault();
+    clOptions.AddFlag("PrecompiledHeader", "NotUsing");
+    std::string asmLocation = configName + "/";
+    clOptions.AddFlag("AssemblerListingLocation", asmLocation.c_str());
+    }
   clOptions.Parse(flags.c_str());
   clOptions.Parse(defineFlags.c_str());
   std::vector<std::string> targetDefines;
   this->Target->GetCompileDefinitions(targetDefines, configName.c_str());
   clOptions.AddDefines(targetDefines);
-  clOptions.SetVerboseMakefile(
-    this->Makefile->IsOn("CMAKE_VERBOSE_MAKEFILE"));
+  if(this->MSTools)
+    {
+    clOptions.SetVerboseMakefile(
+      this->Makefile->IsOn("CMAKE_VERBOSE_MAKEFILE"));
+    }
 
   // Add a definition for the configuration name.
   std::string configDefine = "CMAKE_INTDIR=\"";
@@ -1422,6 +1830,36 @@
     clOptions.AddDefine(exportMacro);
     }
 
+  if (this->MSTools)
+    {
+    // If we have the VS_WINRT_COMPONENT set then force Compile as WinRT.
+    if (this->Target->GetPropertyAsBool("VS_WINRT_COMPONENT"))
+      {
+      clOptions.AddFlag("CompileAsWinRT", "true");
+      // For WinRT components, add the _WINRT_DLL define to produce a lib
+      if (this->Target->GetType() == cmTarget::SHARED_LIBRARY ||
+          this->Target->GetType() == cmTarget::MODULE_LIBRARY )
+        {
+        clOptions.AddDefine("_WINRT_DLL");
+        }
+      }
+    else if (this->GlobalGenerator->TargetsWindowsStore() ||
+             this->GlobalGenerator->TargetsWindowsPhone())
+      {
+      if (!clOptions.IsWinRt())
+        {
+        clOptions.AddFlag("CompileAsWinRT", "false");
+        }
+      }
+    if(const char* winRT = clOptions.GetFlag("CompileAsWinRT"))
+      {
+      if(cmSystemTools::IsOn(winRT))
+        {
+        this->TargetCompileAsWinRT = true;
+        }
+      }
+    }
+
   this->ClOptions[configName] = pOptions.release();
   return true;
 }
@@ -1434,63 +1872,166 @@
   Options& clOptions = *(this->ClOptions[configName]);
   this->WriteString("<ClCompile>\n", 2);
   clOptions.OutputAdditionalOptions(*this->BuildFileStream, "      ", "");
-  this->OutputIncludes(includes);
+  clOptions.AppendFlag("AdditionalIncludeDirectories", includes);
+  clOptions.AppendFlag("AdditionalIncludeDirectories",
+                       "%(AdditionalIncludeDirectories)");
   clOptions.OutputFlagMap(*this->BuildFileStream, "      ");
-
-  // If not in debug mode, write the DebugInformationFormat field
-  // without value so PDBs don't get generated uselessly.
-  if(!clOptions.IsDebug())
-    {
-    this->WriteString("<DebugInformationFormat>"
-                      "</DebugInformationFormat>\n", 3);
-    }
-
   clOptions.OutputPreprocessorDefinitions(*this->BuildFileStream, "      ",
                                           "\n", "CXX");
-  this->WriteString("<ObjectFileName>$(IntDir)</ObjectFileName>\n", 3);
 
-  // Specify the compiler program database file if configured.
-  std::string pdb = this->Target->GetCompilePDBPath(configName.c_str());
-  if(!pdb.empty())
+  if(this->MSTools)
     {
-    this->ConvertToWindowsSlash(pdb);
-    this->WriteString("<ProgramDataBaseFileName>", 3);
-    *this->BuildFileStream << cmVS10EscapeXML(pdb)
-                           << "</ProgramDataBaseFileName>\n";
+    this->WriteString("<ObjectFileName>$(IntDir)</ObjectFileName>\n", 3);
+
+    // If not in debug mode, write the DebugInformationFormat field
+    // without value so PDBs don't get generated uselessly.
+    if(!clOptions.IsDebug())
+      {
+      this->WriteString("<DebugInformationFormat>"
+                        "</DebugInformationFormat>\n", 3);
+      }
+
+    // Specify the compiler program database file if configured.
+    std::string pdb = this->Target->GetCompilePDBPath(configName.c_str());
+    if(!pdb.empty())
+      {
+      this->ConvertToWindowsSlash(pdb);
+      this->WriteString("<ProgramDataBaseFileName>", 3);
+      *this->BuildFileStream << cmVS10EscapeXML(pdb)
+                             << "</ProgramDataBaseFileName>\n";
+      }
     }
 
   this->WriteString("</ClCompile>\n", 2);
 }
 
-void cmVisualStudio10TargetGenerator::
-OutputIncludes(std::vector<std::string> const & includes)
+//----------------------------------------------------------------------------
+bool cmVisualStudio10TargetGenerator::ComputeRcOptions()
 {
-  this->WriteString("<AdditionalIncludeDirectories>", 3);
-  for(std::vector<std::string>::const_iterator i =  includes.begin();
-      i != includes.end(); ++i)
+  std::vector<std::string> const* configs =
+    this->GlobalGenerator->GetConfigurations();
+  for(std::vector<std::string>::const_iterator i = configs->begin();
+      i != configs->end(); ++i)
     {
-    std::string incDir = *i;
-    this->ConvertToWindowsSlash(incDir);
-    *this->BuildFileStream << cmVS10EscapeXML(incDir) << ";";
+    if(!this->ComputeRcOptions(*i))
+      {
+      return false;
+      }
     }
-  this->WriteString("%(AdditionalIncludeDirectories)"
-                    "</AdditionalIncludeDirectories>\n", 0);
+  return true;
 }
 
+//----------------------------------------------------------------------------
+bool cmVisualStudio10TargetGenerator::ComputeRcOptions(
+  std::string const& configName)
+{
+  cmsys::auto_ptr<Options> pOptions(
+    new Options(this->LocalGenerator, Options::ResourceCompiler,
+                this->GetRcFlagTable()));
+  Options& rcOptions = *pOptions;
 
+  std::string CONFIG = cmSystemTools::UpperCase(configName);
+  std::string rcConfigFlagsVar = std::string("CMAKE_RC_FLAGS_") + CONFIG;
+  std::string flags =
+      std::string(this->Makefile->GetSafeDefinition("CMAKE_RC_FLAGS")) +
+      std::string(" ") +
+      std::string(this->Makefile->GetSafeDefinition(rcConfigFlagsVar));
+
+  rcOptions.Parse(flags.c_str());
+  this->RcOptions[configName] = pOptions.release();
+  return true;
+}
 
 void cmVisualStudio10TargetGenerator::
 WriteRCOptions(std::string const& configName,
                std::vector<std::string> const & includes)
 {
+  if(!this->MSTools)
+    {
+    return;
+    }
   this->WriteString("<ResourceCompile>\n", 2);
+
+  // Preprocessor definitions and includes are shared with clOptions.
   Options& clOptions = *(this->ClOptions[configName]);
   clOptions.OutputPreprocessorDefinitions(*this->BuildFileStream, "      ",
                                           "\n", "RC");
-  this->OutputIncludes(includes);
+
+  Options& rcOptions = *(this->RcOptions[configName]);
+  rcOptions.AppendFlag("AdditionalIncludeDirectories", includes);
+  rcOptions.AppendFlag("AdditionalIncludeDirectories",
+                       "%(AdditionalIncludeDirectories)");
+  rcOptions.OutputFlagMap(*this->BuildFileStream, "      ");
+  rcOptions.OutputAdditionalOptions(*this->BuildFileStream, "      ", "");
+
   this->WriteString("</ResourceCompile>\n", 2);
 }
 
+//----------------------------------------------------------------------------
+bool cmVisualStudio10TargetGenerator::ComputeMasmOptions()
+{
+  if(!this->GlobalGenerator->IsMasmEnabled())
+    {
+    return true;
+    }
+  std::vector<std::string> const* configs =
+    this->GlobalGenerator->GetConfigurations();
+  for(std::vector<std::string>::const_iterator i = configs->begin();
+      i != configs->end(); ++i)
+    {
+    if(!this->ComputeMasmOptions(*i))
+      {
+      return false;
+      }
+    }
+  return true;
+}
+
+//----------------------------------------------------------------------------
+bool cmVisualStudio10TargetGenerator::ComputeMasmOptions(
+  std::string const& configName)
+{
+  cmsys::auto_ptr<Options> pOptions(
+    new Options(this->LocalGenerator, Options::MasmCompiler,
+                this->GetMasmFlagTable()));
+  Options& masmOptions = *pOptions;
+
+  std::string CONFIG = cmSystemTools::UpperCase(configName);
+  std::string configFlagsVar = std::string("CMAKE_ASM_MASM_FLAGS_") + CONFIG;
+  std::string flags =
+      std::string(this->Makefile->GetSafeDefinition("CMAKE_ASM_MASM_FLAGS")) +
+      std::string(" ") +
+      std::string(this->Makefile->GetSafeDefinition(configFlagsVar));
+
+  masmOptions.Parse(flags.c_str());
+  this->MasmOptions[configName] = pOptions.release();
+  return true;
+}
+
+void cmVisualStudio10TargetGenerator::
+WriteMasmOptions(std::string const& configName,
+                 std::vector<std::string> const& includes)
+{
+  if(!this->MSTools || !this->GlobalGenerator->IsMasmEnabled())
+    {
+    return;
+    }
+  this->WriteString("<MASM>\n", 2);
+
+  // Preprocessor definitions and includes are shared with clOptions.
+  Options& clOptions = *(this->ClOptions[configName]);
+  clOptions.OutputPreprocessorDefinitions(*this->BuildFileStream, "      ",
+                                          "\n", "ASM_MASM");
+
+  Options& masmOptions = *(this->MasmOptions[configName]);
+  masmOptions.AppendFlag("IncludePaths", includes);
+  masmOptions.AppendFlag("IncludePaths", "%(IncludePaths)");
+  masmOptions.OutputFlagMap(*this->BuildFileStream, "      ");
+  masmOptions.OutputAdditionalOptions(*this->BuildFileStream, "      ", "");
+
+  this->WriteString("</MASM>\n", 2);
+}
+
 
 void
 cmVisualStudio10TargetGenerator::WriteLibOptions(std::string const& config)
@@ -1508,12 +2049,68 @@
     cmVisualStudioGeneratorOptions
       libOptions(this->LocalGenerator,
                  cmVisualStudioGeneratorOptions::Linker,
-                 cmVSGetLibFlagTable(this->LocalGenerator), 0, this);
+                 this->GetLibFlagTable(), 0, this);
     libOptions.Parse(libflags.c_str());
     libOptions.OutputAdditionalOptions(*this->BuildFileStream, "      ", "");
     libOptions.OutputFlagMap(*this->BuildFileStream, "      ");
     this->WriteString("</Lib>\n", 2);
     }
+
+  // We cannot generate metadata for static libraries.  WindowsPhone
+  // and WindowsStore tools look at GenerateWindowsMetadata in the
+  // Link tool options even for static libraries.
+  if(this->GlobalGenerator->TargetsWindowsPhone() ||
+     this->GlobalGenerator->TargetsWindowsStore())
+    {
+    this->WriteString("<Link>\n", 2);
+    this->WriteString("<GenerateWindowsMetadata>false"
+                      "</GenerateWindowsMetadata>\n", 3);
+    this->WriteString("</Link>\n", 2);
+    }
+}
+
+
+//----------------------------------------------------------------------------
+void cmVisualStudio10TargetGenerator::WriteAntBuildOptions(
+  std::string const&)
+{
+  // Look through the sources for AndroidManifest.xml and use
+  // its location as the root source directory.
+  std::string rootDir = this->Makefile->GetCurrentDirectory();
+  {
+  std::vector<cmSourceFile const*> extraSources;
+  this->GeneratorTarget->GetExtraSources(extraSources, "");
+  for(std::vector<cmSourceFile const*>::const_iterator si =
+        extraSources.begin(); si != extraSources.end(); ++si)
+    {
+    if("androidmanifest.xml" == cmSystemTools::LowerCase(
+         (*si)->GetLocation().GetName()))
+      {
+      rootDir = (*si)->GetLocation().GetDirectory();
+      break;
+      }
+    }
+  }
+
+  // Tell MSBuild to launch Ant.
+  {
+  std::string antBuildPath = rootDir;
+  this->WriteString("<AntBuild>\n", 2);
+  this->WriteString("<AntBuildPath>", 3);
+  this->ConvertToWindowsSlash(antBuildPath);
+  (*this->BuildFileStream) <<
+    cmVS10EscapeXML(antBuildPath) << "</AntBuildPath>\n";
+  }
+
+  {
+  std::string manifest_xml = rootDir + "/AndroidManifest.xml";
+  this->ConvertToWindowsSlash(manifest_xml);
+  this->WriteString("<AndroidManifestLocation>", 3);
+  (*this->BuildFileStream) <<
+    cmVS10EscapeXML(manifest_xml) << "</AndroidManifestLocation>\n";
+  }
+
+  this->WriteString("</AntBuild>\n", 2);
 }
 
 //----------------------------------------------------------------------------
@@ -1543,7 +2140,7 @@
 {
   cmsys::auto_ptr<Options> pOptions(
     new Options(this->LocalGenerator, Options::Linker,
-                cmVSGetLinkFlagTable(this->LocalGenerator), 0, this));
+                this->GetLinkFlagTable(), 0, this));
   Options& linkOptions = *pOptions;
 
   const std::string& linkLanguage =
@@ -1567,16 +2164,7 @@
     {
     linkType = "EXE";
     }
-  std::string stackVar = "CMAKE_";
-  stackVar += linkLanguage;
-  stackVar += "_STACK_SIZE";
-  const char* stackVal = this->Makefile->GetDefinition(stackVar.c_str());
   std::string flags;
-  if(stackVal)
-    {
-    flags += " /STACK:";
-    flags += stackVal;
-    }
   std::string linkFlagVarBase = "CMAKE_";
   linkFlagVarBase += linkType;
   linkFlagVarBase += "_LINKER_FLAGS";
@@ -1600,14 +2188,6 @@
     flags += " ";
     flags += flagsConfig;
     }
-  if ( this->Target->GetPropertyAsBool("WIN32_EXECUTABLE") )
-    {
-    linkOptions.AddFlag("SubSystem", "Windows");
-    }
-  else
-    {
-    linkOptions.AddFlag("SubSystem", "Console");
-    }
   std::string standardLibsVar = "CMAKE_";
   standardLibsVar += linkLanguage;
   standardLibsVar += "_STANDARD_LIBRARIES";
@@ -1628,6 +2208,9 @@
     }
   // Replace spaces in libs with ;
   cmSystemTools::ReplaceString(libs, " ", ";");
+  std::vector<std::string> libVec;
+  cmSystemTools::ExpandListArgument(libs, libVec);
+
   cmComputeLinkInformation* pcli =
     this->Target->GetLinkInformation(config.c_str());
   if(!pcli)
@@ -1639,37 +2222,22 @@
     }
   // add the libraries for the target to libs string
   cmComputeLinkInformation& cli = *pcli;
-  this->AddLibraries(cli, libs);
-  linkOptions.AddFlag("AdditionalDependencies", libs.c_str());
+  this->AddLibraries(cli, libVec);
+  linkOptions.AddFlag("AdditionalDependencies", libVec);
 
   std::vector<std::string> const& ldirs = cli.GetDirectories();
-  const char* sep = "";
-  std::string linkDirs;
+  std::vector<std::string> linkDirs;
   for(std::vector<std::string>::const_iterator d = ldirs.begin();
       d != ldirs.end(); ++d)
     {
     // first just full path
-    linkDirs += sep;
-    linkDirs += *d;
-    sep = ";";
-    linkDirs += sep;
+    linkDirs.push_back(*d);
     // next path with configuration type Debug, Release, etc
-    linkDirs += *d;
-    linkDirs += "/$(Configuration)";
-    linkDirs += sep;
+    linkDirs.push_back(*d + "/$(Configuration)");
     }
-  linkDirs += "%(AdditionalLibraryDirectories)";
-  linkOptions.AddFlag("AdditionalLibraryDirectories", linkDirs.c_str());
-  linkOptions.AddFlag("AdditionalDependencies", libs.c_str());
-  linkOptions.AddFlag("Version", "");
-  if(linkOptions.IsDebug() || flags.find("/debug") != flags.npos)
-    {
-    linkOptions.AddFlag("GenerateDebugInformation", "true");
-    }
-  else
-    {
-    linkOptions.AddFlag("GenerateDebugInformation", "false");
-    }
+  linkDirs.push_back("%(AdditionalLibraryDirectories)");
+  linkOptions.AddFlag("AdditionalLibraryDirectories", linkDirs);
+
   std::string targetName;
   std::string targetNameSO;
   std::string targetNameFull;
@@ -1688,20 +2256,103 @@
                                   config.c_str());
     }
 
-  std::string pdb = this->Target->GetPDBDirectory(config.c_str());
-  pdb += "/";
-  pdb += targetNamePDB;
-  std::string imLib = this->Target->GetDirectory(config.c_str(), true);
-  imLib += "/";
-  imLib += targetNameImport;
-
-  linkOptions.AddFlag("ImportLibrary", imLib.c_str());
-  linkOptions.AddFlag("ProgramDataBaseFile", pdb.c_str());
-  linkOptions.Parse(flags.c_str());
-  std::string def = this->GeneratorTarget->GetModuleDefinitionFile("");
-  if(!def.empty())
+  if(this->MSTools)
     {
-    linkOptions.AddFlag("ModuleDefinitionFile", def.c_str());
+    linkOptions.AddFlag("Version", "");
+
+    if ( this->Target->GetPropertyAsBool("WIN32_EXECUTABLE") )
+      {
+      if (this->GlobalGenerator->TargetsWindowsCE())
+        {
+        linkOptions.AddFlag("SubSystem", "WindowsCE");
+        if (this->Target->GetType() == cmTarget::EXECUTABLE)
+          {
+          linkOptions.AddFlag("EntryPointSymbol", "WinMainCRTStartup");
+          }
+        }
+      else
+        {
+        linkOptions.AddFlag("SubSystem", "Windows");
+        }
+      }
+    else
+      {
+      if (this->GlobalGenerator->TargetsWindowsCE())
+        {
+        linkOptions.AddFlag("SubSystem", "WindowsCE");
+        if (this->Target->GetType() == cmTarget::EXECUTABLE)
+          {
+          linkOptions.AddFlag("EntryPointSymbol", "mainACRTStartup");
+          }
+        }
+      else
+        {
+        linkOptions.AddFlag("SubSystem", "Console");
+        };
+      }
+
+    if(const char* stackVal =
+       this->Makefile->GetDefinition("CMAKE_"+linkLanguage+"_STACK_SIZE"))
+      {
+      linkOptions.AddFlag("StackReserveSize", stackVal);
+      }
+
+    if(linkOptions.IsDebug() || flags.find("/debug") != flags.npos)
+      {
+      linkOptions.AddFlag("GenerateDebugInformation", "true");
+      }
+    else
+      {
+      linkOptions.AddFlag("GenerateDebugInformation", "false");
+      }
+    std::string pdb = this->Target->GetPDBDirectory(config.c_str());
+    pdb += "/";
+    pdb += targetNamePDB;
+    std::string imLib = this->Target->GetDirectory(config.c_str(), true);
+    imLib += "/";
+    imLib += targetNameImport;
+
+    linkOptions.AddFlag("ImportLibrary", imLib.c_str());
+    linkOptions.AddFlag("ProgramDataBaseFile", pdb.c_str());
+
+    // A Windows Runtime component uses internal .NET metadata,
+    // so does not have an import library.
+    if(this->Target->GetPropertyAsBool("VS_WINRT_COMPONENT"))
+      {
+      linkOptions.AddFlag("GenerateWindowsMetadata", "true");
+      }
+    else if (this->GlobalGenerator->TargetsWindowsPhone() ||
+             this->GlobalGenerator->TargetsWindowsStore())
+      {
+      // WindowsPhone and WindowsStore components are in an app container
+      // and produce WindowsMetadata.  If we are not producing a WINRT
+      // component, then do not generate the metadata here.
+      linkOptions.AddFlag("GenerateWindowsMetadata", "false");
+      }
+
+    if (this->GlobalGenerator->TargetsWindowsPhone() &&
+        this->GlobalGenerator->GetSystemVersion() == "8.0")
+      {
+      // WindowsPhone 8.0 does not have ole32.
+      linkOptions.AppendFlag("IgnoreSpecificDefaultLibraries", "ole32.lib");
+      }
+    }
+  else if(this->NsightTegra)
+    {
+    linkOptions.AddFlag("SoName", targetNameSO.c_str());
+    }
+
+  linkOptions.Parse(flags.c_str());
+
+  if(this->MSTools)
+    {
+    std::string def = this->GeneratorTarget->GetModuleDefinitionFile("");
+    if(!def.empty())
+      {
+      linkOptions.AddFlag("ModuleDefinitionFile", def.c_str());
+      }
+    linkOptions.AppendFlag("IgnoreSpecificDefaultLibraries",
+                           "%(IgnoreSpecificDefaultLibraries)");
     }
 
   this->LinkOptions[config] = pOptions.release();
@@ -1735,11 +2386,10 @@
 
 void cmVisualStudio10TargetGenerator::AddLibraries(
   cmComputeLinkInformation& cli,
-  std::string& libstring)
+  std::vector<std::string>& libVec)
 {
   typedef cmComputeLinkInformation::ItemVector ItemVector;
   ItemVector libs = cli.GetItems();
-  const char* sep = ";";
   for(ItemVector::const_iterator l = libs.begin(); l != libs.end(); ++l)
     {
     if(l->IsPath)
@@ -1749,14 +2399,12 @@
                 cmLocalGenerator::START_OUTPUT,
                 cmLocalGenerator::UNCHANGED);
       this->ConvertToWindowsSlash(path);
-      libstring += sep;
-      libstring += path;
+      libVec.push_back(path);
       }
     else if (!l->Target
         || l->Target->GetType() != cmTarget::INTERFACE_LIBRARY)
       {
-      libstring += sep;
-      libstring += l->Value;
+      libVec.push_back(l->Value);
       }
     }
 }
@@ -1766,6 +2414,11 @@
 WriteMidlOptions(std::string const& /*config*/,
                  std::vector<std::string> const & includes)
 {
+  if(!this->MSTools)
+    {
+    return;
+    }
+
   // This processes *any* of the .idl files specified in the project's file
   // list (and passed as the item metadata %(Filename) expressing the rule
   // input filename) into output files at the per-config *build* dir
@@ -1782,7 +2435,14 @@
   // only).  Perhaps there's something to be done to make this more automatic
   // on the CMake side?
   this->WriteString("<Midl>\n", 2);
-  this->OutputIncludes(includes);
+  this->WriteString("<AdditionalIncludeDirectories>", 3);
+  for(std::vector<std::string>::const_iterator i =  includes.begin();
+      i != includes.end(); ++i)
+    {
+    *this->BuildFileStream << cmVS10EscapeXML(*i) << ";";
+    }
+  this->WriteString("%(AdditionalIncludeDirectories)"
+                    "</AdditionalIncludeDirectories>\n", 0);
   this->WriteString("<OutputDirectory>$(IntDir)</OutputDirectory>\n", 3);
   this->WriteString("<HeaderFileName>%(Filename).h</HeaderFileName>\n", 3);
   this->WriteString(
@@ -1807,6 +2467,11 @@
     this->LocalGenerator->GetIncludeDirectories(includes,
                                                 this->GeneratorTarget,
                                                 "C", i->c_str());
+    for(std::vector<std::string>::iterator ii = includes.begin();
+        ii != includes.end(); ++ii)
+      {
+      this->ConvertToWindowsSlash(*ii);
+      }
     this->WritePlatformConfigTag("ItemDefinitionGroup", i->c_str(), 1);
     *this->BuildFileStream << "\n";
     //    output cl compile flags <ClCompile></ClCompile>
@@ -1815,6 +2480,7 @@
       this->WriteClOptions(*i, includes);
       //    output rc compile flags <ResourceCompile></ResourceCompile>
       this->WriteRCOptions(*i, includes);
+      this->WriteMasmOptions(*i, includes);
       }
     //    output midl flags       <Midl></Midl>
     this->WriteMidlOptions(*i, includes);
@@ -1824,6 +2490,12 @@
     this->WriteLinkOptions(*i);
     //    output lib flags       <Lib></Lib>
     this->WriteLibOptions(*i);
+    if(this->NsightTegra &&
+       this->Target->GetType() == cmTarget::EXECUTABLE &&
+       this->Target->GetPropertyAsBool("ANDROID_GUI"))
+      {
+      this->WriteAntBuildOptions(*i);
+      }
     this->WriteString("</ItemDefinitionGroup>\n", 1);
     }
 }
@@ -1914,7 +2586,7 @@
       path += dt->GetName();
       path += ".vcxproj";
       }
-    (*this->BuildFileStream) << path << "\">\n";
+    (*this->BuildFileStream) << cmVS10EscapeXML(path) << "\">\n";
     this->WriteString("<Project>", 3);
     (*this->BuildFileStream)
       << this->GlobalGenerator->GetGUID(name.c_str())
@@ -1924,6 +2596,67 @@
   this->WriteString("</ItemGroup>\n", 1);
 }
 
+void cmVisualStudio10TargetGenerator::WriteWinRTPackageCertificateKeyFile()
+{
+  if((this->GlobalGenerator->TargetsWindowsStore() ||
+      this->GlobalGenerator->TargetsWindowsPhone())
+      && (cmTarget::EXECUTABLE == this->Target->GetType()))
+    {
+    std::string pfxFile;
+    std::vector<cmSourceFile const*> certificates;
+    this->GeneratorTarget->GetCertificates(certificates, "");
+    for(std::vector<cmSourceFile const*>::const_iterator si =
+        certificates.begin(); si != certificates.end(); ++si)
+      {
+      pfxFile = this->ConvertPath((*si)->GetFullPath(), false);
+      this->ConvertToWindowsSlash(pfxFile);
+      break;
+      }
+
+    if(this->IsMissingFiles &&
+       !(this->GlobalGenerator->TargetsWindowsPhone() &&
+         this->GlobalGenerator->GetSystemVersion() == "8.0"))
+      {
+      // Move the manifest to a project directory to avoid clashes
+      std::string artifactDir =
+        this->LocalGenerator->GetTargetDirectory(*this->Target);
+      this->ConvertToWindowsSlash(artifactDir);
+      this->WriteString("<PropertyGroup>\n", 1);
+      this->WriteString("<AppxPackageArtifactsDir>", 2);
+      (*this->BuildFileStream) << cmVS10EscapeXML(artifactDir) <<
+        "\\</AppxPackageArtifactsDir>\n";
+      this->WriteString("<ProjectPriFullPath>"
+        "$(TargetDir)resources.pri</ProjectPriFullPath>", 2);
+
+      // If we are missing files and we don't have a certificate and
+      // aren't targeting WP8.0, add a default certificate
+      if(pfxFile.empty())
+        {
+        std::string templateFolder = cmSystemTools::GetCMakeRoot() +
+                                     "/Templates/Windows";
+        pfxFile = this->DefaultArtifactDir + "/Windows_TemporaryKey.pfx";
+        cmSystemTools::CopyAFile(templateFolder + "/Windows_TemporaryKey.pfx",
+                                 pfxFile, false);
+        this->ConvertToWindowsSlash(pfxFile);
+        this->AddedFiles.push_back(pfxFile);
+        }
+
+      this->WriteString("<", 2);
+      (*this->BuildFileStream) << "PackageCertificateKeyFile>"
+        << pfxFile << "</PackageCertificateKeyFile>\n";
+      this->WriteString("</PropertyGroup>\n", 1);
+      }
+    else if(!pfxFile.empty())
+      {
+      this->WriteString("<PropertyGroup>\n", 1);
+      this->WriteString("<", 2);
+      (*this->BuildFileStream) << "PackageCertificateKeyFile>"
+        << pfxFile << "</PackageCertificateKeyFile>\n";
+      this->WriteString("</PropertyGroup>\n", 1);
+      }
+    }
+}
+
 bool cmVisualStudio10TargetGenerator::
   IsResxHeader(const std::string& headerFile)
 {
@@ -1934,3 +2667,460 @@
                                         expectedResxHeaders.find(headerFile);
   return it != expectedResxHeaders.end();
 }
+
+void cmVisualStudio10TargetGenerator::WriteApplicationTypeSettings()
+{
+  bool isAppContainer = false;
+  bool const isWindowsPhone = this->GlobalGenerator->TargetsWindowsPhone();
+  bool const isWindowsStore = this->GlobalGenerator->TargetsWindowsStore();
+  std::string const& v = this->GlobalGenerator->GetSystemVersion();
+  if(isWindowsPhone || isWindowsStore)
+    {
+    this->WriteString("<ApplicationType>", 2);
+    (*this->BuildFileStream) << (isWindowsPhone ?
+                                 "Windows Phone" : "Windows Store")
+                             << "</ApplicationType>\n";
+    this->WriteString("<ApplicationTypeRevision>", 2);
+    (*this->BuildFileStream) << cmVS10EscapeXML(v)
+                             << "</ApplicationTypeRevision>\n";
+    if(v == "8.1")
+      {
+      // Visual Studio 12.0 is necessary for building 8.1 apps
+      this->WriteString("<MinimumVisualStudioVersion>12.0"
+                        "</MinimumVisualStudioVersion>\n", 2);
+
+      if (this->Target->GetType() < cmTarget::UTILITY)
+        {
+        isAppContainer = true;
+        }
+      }
+    else if (v == "8.0")
+      {
+      // Visual Studio 11.0 is necessary for building 8.0 apps
+      this->WriteString("<MinimumVisualStudioVersion>11.0"
+                        "</MinimumVisualStudioVersion>\n", 2);
+
+      if (isWindowsStore && this->Target->GetType() < cmTarget::UTILITY)
+        {
+        isAppContainer = true;
+        }
+      else if (isWindowsPhone &&
+               this->Target->GetType() == cmTarget::EXECUTABLE)
+        {
+        this->WriteString("<XapOutputs>true</XapOutputs>\n", 2);
+        this->WriteString("<XapFilename>", 2);
+        (*this->BuildFileStream) << cmVS10EscapeXML(this->Name.c_str()) <<
+           "_$(Configuration)_$(Platform).xap</XapFilename>\n";
+        }
+      }
+    }
+  if(isAppContainer)
+    {
+    this->WriteString("<AppContainerApplication>true"
+                      "</AppContainerApplication>", 2);
+    }
+  else if (this->Platform == "ARM")
+    {
+    this->WriteString("<WindowsSDKDesktopARMSupport>true"
+                      "</WindowsSDKDesktopARMSupport>", 2);
+    }
+}
+
+void cmVisualStudio10TargetGenerator::VerifyNecessaryFiles()
+{
+  // For Windows and Windows Phone executables, we will assume that if a
+  // manifest is not present that we need to add all the necessary files
+  if (this->Target->GetType() == cmTarget::EXECUTABLE)
+    {
+    std::vector<cmSourceFile const*> manifestSources;
+    this->GeneratorTarget->GetAppManifest(manifestSources, "");
+      {
+      std::string const& v = this->GlobalGenerator->GetSystemVersion();
+      if(this->GlobalGenerator->TargetsWindowsPhone())
+        {
+        if (v == "8.0")
+          {
+          // Look through the sources for WMAppManifest.xml
+          std::vector<cmSourceFile const*> extraSources;
+          this->GeneratorTarget->GetExtraSources(extraSources, "");
+          bool foundManifest = false;
+          for(std::vector<cmSourceFile const*>::const_iterator si =
+            extraSources.begin(); si != extraSources.end(); ++si)
+            {
+            // Need to do a lowercase comparison on the filename
+            if("wmappmanifest.xml" == cmSystemTools::LowerCase(
+              (*si)->GetLocation().GetName()))
+              {
+              foundManifest = true;
+              break;
+              }
+            }
+          if (!foundManifest)
+            {
+            this->IsMissingFiles = true;
+            }
+          }
+        else if (v == "8.1")
+          {
+          if(manifestSources.empty())
+            {
+            this->IsMissingFiles = true;
+            }
+          }
+        }
+      else if (this->GlobalGenerator->TargetsWindowsStore())
+        {
+        if (manifestSources.empty())
+          {
+          if (v == "8.0")
+            {
+            this->IsMissingFiles = true;
+            }
+          else if (v == "8.1")
+            {
+            this->IsMissingFiles = true;
+            }
+          }
+        }
+      }
+    }
+}
+
+void cmVisualStudio10TargetGenerator::WriteMissingFiles()
+{
+  std::string const& v = this->GlobalGenerator->GetSystemVersion();
+  if(this->GlobalGenerator->TargetsWindowsPhone())
+    {
+    if (v == "8.0")
+      {
+      this->WriteMissingFilesWP80();
+      }
+    else if (v == "8.1")
+      {
+      this->WriteMissingFilesWP81();
+      }
+    }
+  else if (this->GlobalGenerator->TargetsWindowsStore())
+   {
+   if (v == "8.0")
+     {
+     this->WriteMissingFilesWS80();
+     }
+   else if (v == "8.1")
+     {
+     this->WriteMissingFilesWS81();
+     }
+   }
+}
+
+void cmVisualStudio10TargetGenerator::WriteMissingFilesWP80()
+{
+  std::string templateFolder = cmSystemTools::GetCMakeRoot() +
+                               "/Templates/Windows";
+
+  // For WP80, the manifest needs to be in the same folder as the project
+  // this can cause an overwrite problem if projects aren't organized in
+  // folders
+  std::string manifestFile = this->Makefile->GetStartOutputDirectory() +
+                             std::string("/WMAppManifest.xml");
+  std::string artifactDir =
+    this->LocalGenerator->GetTargetDirectory(*this->Target);
+  this->ConvertToWindowsSlash(artifactDir);
+  std::string artifactDirXML = cmVS10EscapeXML(artifactDir);
+  std::string targetNameXML = cmVS10EscapeXML(this->Target->GetName());
+
+  cmGeneratedFileStream fout(manifestFile.c_str());
+  fout.SetCopyIfDifferent(true);
+
+  fout <<
+    "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
+    "<Deployment"
+    " xmlns=\"http://schemas.microsoft.com/windowsphone/2012/deployment\""
+    " AppPlatformVersion=\"8.0\">\n"
+    "\t<DefaultLanguage xmlns=\"\" code=\"en-US\"/>\n"
+    "\t<App xmlns=\"\" ProductID=\"{" << this->GUID << "}\""
+    " Title=\"CMake Test Program\" RuntimeType=\"Modern Native\""
+    " Version=\"1.0.0.0\" Genre=\"apps.normal\"  Author=\"CMake\""
+    " Description=\"Default CMake App\" Publisher=\"CMake\""
+    " PublisherID=\"{" << this->GUID << "}\">\n"
+    "\t\t<IconPath IsRelative=\"true\" IsResource=\"false\">"
+       << artifactDirXML << "\\ApplicationIcon.png</IconPath>\n"
+    "\t\t<Capabilities/>\n"
+    "\t\t<Tasks>\n"
+    "\t\t\t<DefaultTask Name=\"_default\""
+    " ImagePath=\"" << targetNameXML << ".exe\" ImageParams=\"\" />\n"
+    "\t\t</Tasks>\n"
+    "\t\t<Tokens>\n"
+    "\t\t\t<PrimaryToken TokenID=\"" << targetNameXML << "Token\""
+    " TaskName=\"_default\">\n"
+    "\t\t\t\t<TemplateFlip>\n"
+    "\t\t\t\t\t<SmallImageURI IsRelative=\"true\" IsResource=\"false\">"
+       << artifactDirXML << "\\SmallLogo.png</SmallImageURI>\n"
+    "\t\t\t\t\t<Count>0</Count>\n"
+    "\t\t\t\t\t<BackgroundImageURI IsRelative=\"true\" IsResource=\"false\">"
+       << artifactDirXML << "\\Logo.png</BackgroundImageURI>\n"
+    "\t\t\t\t</TemplateFlip>\n"
+    "\t\t\t</PrimaryToken>\n"
+    "\t\t</Tokens>\n"
+    "\t\t<ScreenResolutions>\n"
+    "\t\t\t<ScreenResolution Name=\"ID_RESOLUTION_WVGA\" />\n"
+    "\t\t</ScreenResolutions>\n"
+    "\t</App>\n"
+    "</Deployment>\n";
+
+  std::string sourceFile = this->ConvertPath(manifestFile, false);
+  this->ConvertToWindowsSlash(sourceFile);
+  this->WriteString("<Xml Include=\"", 2);
+  (*this->BuildFileStream) << cmVS10EscapeXML(sourceFile) << "\">\n";
+  this->WriteString("<SubType>Designer</SubType>\n", 3);
+  this->WriteString("</Xml>\n", 2);
+  this->AddedFiles.push_back(sourceFile);
+
+  std::string smallLogo = this->DefaultArtifactDir + "/SmallLogo.png";
+  cmSystemTools::CopyAFile(templateFolder + "/SmallLogo.png",
+                           smallLogo, false);
+  this->ConvertToWindowsSlash(smallLogo);
+  this->WriteString("<Image Include=\"", 2);
+  (*this->BuildFileStream) << cmVS10EscapeXML(smallLogo) << "\" />\n";
+  this->AddedFiles.push_back(smallLogo);
+
+  std::string logo = this->DefaultArtifactDir + "/Logo.png";
+  cmSystemTools::CopyAFile(templateFolder + "/Logo.png",
+                           logo, false);
+  this->ConvertToWindowsSlash(logo);
+  this->WriteString("<Image Include=\"", 2);
+  (*this->BuildFileStream) << cmVS10EscapeXML(logo) << "\" />\n";
+  this->AddedFiles.push_back(logo);
+
+  std::string applicationIcon =
+    this->DefaultArtifactDir + "/ApplicationIcon.png";
+  cmSystemTools::CopyAFile(templateFolder + "/ApplicationIcon.png",
+                           applicationIcon, false);
+  this->ConvertToWindowsSlash(applicationIcon);
+  this->WriteString("<Image Include=\"", 2);
+  (*this->BuildFileStream) << cmVS10EscapeXML(applicationIcon) << "\" />\n";
+  this->AddedFiles.push_back(applicationIcon);
+}
+
+void cmVisualStudio10TargetGenerator::WriteMissingFilesWP81()
+{
+  std::string manifestFile =
+    this->DefaultArtifactDir + "/package.appxManifest";
+  std::string artifactDir =
+    this->LocalGenerator->GetTargetDirectory(*this->Target);
+  this->ConvertToWindowsSlash(artifactDir);
+  std::string artifactDirXML = cmVS10EscapeXML(artifactDir);
+  std::string targetNameXML = cmVS10EscapeXML(this->Target->GetName());
+
+  cmGeneratedFileStream fout(manifestFile.c_str());
+  fout.SetCopyIfDifferent(true);
+
+  fout <<
+    "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
+    "<Package xmlns=\"http://schemas.microsoft.com/appx/2010/manifest\""
+    " xmlns:m2=\"http://schemas.microsoft.com/appx/2013/manifest\""
+    " xmlns:mp=\"http://schemas.microsoft.com/appx/2014/phone/manifest\">\n"
+    "\t<Identity Name=\"" << this->GUID << "\" Publisher=\"CN=CMake\""
+    " Version=\"1.0.0.0\" />\n"
+    "\t<mp:PhoneIdentity PhoneProductId=\"" << this->GUID << "\""
+    " PhonePublisherId=\"00000000-0000-0000-0000-000000000000\"/>\n"
+    "\t<Properties>\n"
+    "\t\t<DisplayName>" << targetNameXML << "</DisplayName>\n"
+    "\t\t<PublisherDisplayName>CMake</PublisherDisplayName>\n"
+    "\t\t<Logo>" << artifactDirXML << "\\StoreLogo.png</Logo>\n"
+    "\t</Properties>\n"
+    "\t<Prerequisites>\n"
+    "\t\t<OSMinVersion>6.3.1</OSMinVersion>\n"
+    "\t\t<OSMaxVersionTested>6.3.1</OSMaxVersionTested>\n"
+    "\t</Prerequisites>\n"
+    "\t<Resources>\n"
+    "\t\t<Resource Language=\"x-generate\" />\n"
+    "\t</Resources>\n"
+    "\t<Applications>\n"
+    "\t\t<Application Id=\"App\""
+    " Executable=\"" << targetNameXML << ".exe\""
+    " EntryPoint=\"" << targetNameXML << ".App\">\n"
+    "\t\t\t<m2:VisualElements\n"
+    "\t\t\t\tDisplayName=\"" << targetNameXML << "\"\n"
+    "\t\t\t\tDescription=\"" << targetNameXML << "\"\n"
+    "\t\t\t\tBackgroundColor=\"#336699\"\n"
+    "\t\t\t\tForegroundText=\"light\"\n"
+    "\t\t\t\tSquare150x150Logo=\"" << artifactDirXML << "\\Logo.png\"\n"
+    "\t\t\t\tSquare30x30Logo=\"" << artifactDirXML << "\\SmallLogo.png\">\n"
+    "\t\t\t\t<m2:DefaultTile ShortName=\"" << targetNameXML << "\">\n"
+    "\t\t\t\t\t<m2:ShowNameOnTiles>\n"
+    "\t\t\t\t\t\t<m2:ShowOn Tile=\"square150x150Logo\" />\n"
+    "\t\t\t\t\t</m2:ShowNameOnTiles>\n"
+    "\t\t\t\t</m2:DefaultTile>\n"
+    "\t\t\t\t<m2:SplashScreen"
+    " Image=\"" << artifactDirXML << "\\SplashScreen.png\" />\n"
+    "\t\t\t</m2:VisualElements>\n"
+    "\t\t</Application>\n"
+    "\t</Applications>\n"
+    "</Package>\n";
+
+  this->WriteCommonMissingFiles(manifestFile);
+}
+
+void cmVisualStudio10TargetGenerator::WriteMissingFilesWS80()
+{
+  std::string manifestFile =
+    this->DefaultArtifactDir + "/package.appxManifest";
+  std::string artifactDir =
+    this->LocalGenerator->GetTargetDirectory(*this->Target);
+  this->ConvertToWindowsSlash(artifactDir);
+  std::string artifactDirXML = cmVS10EscapeXML(artifactDir);
+  std::string targetNameXML = cmVS10EscapeXML(this->Target->GetName());
+
+  cmGeneratedFileStream fout(manifestFile.c_str());
+  fout.SetCopyIfDifferent(true);
+
+  fout <<
+    "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
+    "<Package xmlns=\"http://schemas.microsoft.com/appx/2010/manifest\">\n"
+    "\t<Identity Name=\"" << this->GUID << "\" Publisher=\"CN=CMake\""
+    " Version=\"1.0.0.0\" />\n"
+    "\t<Properties>\n"
+    "\t\t<DisplayName>" << targetNameXML << "</DisplayName>\n"
+    "\t\t<PublisherDisplayName>CMake</PublisherDisplayName>\n"
+    "\t\t<Logo>" << artifactDirXML << "\\StoreLogo.png</Logo>\n"
+    "\t</Properties>\n"
+    "\t<Prerequisites>\n"
+    "\t\t<OSMinVersion>6.2.1</OSMinVersion>\n"
+    "\t\t<OSMaxVersionTested>6.2.1</OSMaxVersionTested>\n"
+    "\t</Prerequisites>\n"
+    "\t<Resources>\n"
+    "\t\t<Resource Language=\"x-generate\" />\n"
+    "\t</Resources>\n"
+    "\t<Applications>\n"
+    "\t\t<Application Id=\"App\""
+    " Executable=\"" << targetNameXML << ".exe\""
+    " EntryPoint=\"" << targetNameXML << ".App\">\n"
+    "\t\t\t<VisualElements"
+    " DisplayName=\"" << targetNameXML << "\""
+    " Description=\"" << targetNameXML << "\""
+    " BackgroundColor=\"#336699\" ForegroundText=\"light\""
+    " Logo=\"" << artifactDirXML << "\\Logo.png\""
+    " SmallLogo=\"" << artifactDirXML << "\\SmallLogo.png\">\n"
+    "\t\t\t\t<DefaultTile ShowName=\"allLogos\""
+    " ShortName=\"" << targetNameXML << "\" />\n"
+    "\t\t\t\t<SplashScreen"
+    " Image=\"" << artifactDirXML << "\\SplashScreen.png\" />\n"
+    "\t\t\t</VisualElements>\n"
+    "\t\t</Application>\n"
+    "\t</Applications>\n"
+    "</Package>\n";
+
+  this->WriteCommonMissingFiles(manifestFile);
+}
+
+void cmVisualStudio10TargetGenerator::WriteMissingFilesWS81()
+{
+  std::string manifestFile =
+    this->DefaultArtifactDir + "/package.appxManifest";
+  std::string artifactDir =
+    this->LocalGenerator->GetTargetDirectory(*this->Target);
+  this->ConvertToWindowsSlash(artifactDir);
+  std::string artifactDirXML = cmVS10EscapeXML(artifactDir);
+  std::string targetNameXML = cmVS10EscapeXML(this->Target->GetName());
+
+  cmGeneratedFileStream fout(manifestFile.c_str());
+  fout.SetCopyIfDifferent(true);
+
+  fout <<
+    "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
+    "<Package xmlns=\"http://schemas.microsoft.com/appx/2010/manifest\""
+    " xmlns:m2=\"http://schemas.microsoft.com/appx/2013/manifest\">\n"
+    "\t<Identity Name=\"" << this->GUID << "\" Publisher=\"CN=CMake\""
+    " Version=\"1.0.0.0\" />\n"
+    "\t<Properties>\n"
+    "\t\t<DisplayName>" << targetNameXML << "</DisplayName>\n"
+    "\t\t<PublisherDisplayName>CMake</PublisherDisplayName>\n"
+    "\t\t<Logo>" << artifactDirXML << "\\StoreLogo.png</Logo>\n"
+    "\t</Properties>\n"
+    "\t<Prerequisites>\n"
+    "\t\t<OSMinVersion>6.3</OSMinVersion>\n"
+    "\t\t<OSMaxVersionTested>6.3</OSMaxVersionTested>\n"
+    "\t</Prerequisites>\n"
+    "\t<Resources>\n"
+    "\t\t<Resource Language=\"x-generate\" />\n"
+    "\t</Resources>\n"
+    "\t<Applications>\n"
+    "\t\t<Application Id=\"App\""
+    " Executable=\"" << targetNameXML << ".exe\""
+    " EntryPoint=\"" << targetNameXML << ".App\">\n"
+    "\t\t\t<m2:VisualElements\n"
+    "\t\t\t\tDisplayName=\"" << targetNameXML << "\"\n"
+    "\t\t\t\tDescription=\"" << targetNameXML << "\"\n"
+    "\t\t\t\tBackgroundColor=\"#336699\"\n"
+    "\t\t\t\tForegroundText=\"light\"\n"
+    "\t\t\t\tSquare150x150Logo=\"" << artifactDirXML << "\\Logo.png\"\n"
+    "\t\t\t\tSquare30x30Logo=\"" << artifactDirXML << "\\SmallLogo.png\">\n"
+    "\t\t\t\t<m2:DefaultTile ShortName=\"" << targetNameXML << "\">\n"
+    "\t\t\t\t\t<m2:ShowNameOnTiles>\n"
+    "\t\t\t\t\t\t<m2:ShowOn Tile=\"square150x150Logo\" />\n"
+    "\t\t\t\t\t</m2:ShowNameOnTiles>\n"
+    "\t\t\t\t</m2:DefaultTile>\n"
+    "\t\t\t\t<m2:SplashScreen"
+    " Image=\"" << artifactDirXML << "\\SplashScreen.png\" />\n"
+    "\t\t\t</m2:VisualElements>\n"
+    "\t\t</Application>\n"
+    "\t</Applications>\n"
+    "</Package>\n";
+
+  this->WriteCommonMissingFiles(manifestFile);
+}
+
+void
+cmVisualStudio10TargetGenerator
+::WriteCommonMissingFiles(const std::string& manifestFile)
+{
+  std::string templateFolder = cmSystemTools::GetCMakeRoot() +
+                               "/Templates/Windows";
+
+  std::string sourceFile = this->ConvertPath(manifestFile, false);
+  this->ConvertToWindowsSlash(sourceFile);
+  this->WriteString("<AppxManifest Include=\"", 2);
+  (*this->BuildFileStream) << cmVS10EscapeXML(sourceFile) << "\">\n";
+  this->WriteString("<SubType>Designer</SubType>\n", 3);
+  this->WriteString("</AppxManifest>\n", 2);
+  this->AddedFiles.push_back(sourceFile);
+
+  std::string smallLogo = this->DefaultArtifactDir + "/SmallLogo.png";
+  cmSystemTools::CopyAFile(templateFolder + "/SmallLogo.png",
+                           smallLogo, false);
+  this->ConvertToWindowsSlash(smallLogo);
+  this->WriteString("<Image Include=\"", 2);
+  (*this->BuildFileStream) << cmVS10EscapeXML(smallLogo) << "\" />\n";
+  this->AddedFiles.push_back(smallLogo);
+
+  std::string logo = this->DefaultArtifactDir + "/Logo.png";
+  cmSystemTools::CopyAFile(templateFolder + "/Logo.png",
+                           logo, false);
+  this->ConvertToWindowsSlash(logo);
+  this->WriteString("<Image Include=\"", 2);
+  (*this->BuildFileStream) << cmVS10EscapeXML(logo) << "\" />\n";
+  this->AddedFiles.push_back(logo);
+
+  std::string storeLogo = this->DefaultArtifactDir + "/StoreLogo.png";
+  cmSystemTools::CopyAFile(templateFolder + "/StoreLogo.png",
+                           storeLogo, false);
+  this->ConvertToWindowsSlash(storeLogo);
+  this->WriteString("<Image Include=\"", 2);
+  (*this->BuildFileStream) << cmVS10EscapeXML(storeLogo) << "\" />\n";
+  this->AddedFiles.push_back(storeLogo);
+
+  std::string splashScreen = this->DefaultArtifactDir + "/SplashScreen.png";
+  cmSystemTools::CopyAFile(templateFolder + "/SplashScreen.png",
+                           splashScreen, false);
+  this->ConvertToWindowsSlash(splashScreen);
+  this->WriteString("<Image Include=\"", 2);
+  (*this->BuildFileStream) << cmVS10EscapeXML(splashScreen) << "\" />\n";
+  this->AddedFiles.push_back(splashScreen);
+
+  // This file has already been added to the build so don't copy it
+  std::string keyFile = this->DefaultArtifactDir + "/Windows_TemporaryKey.pfx";
+  this->ConvertToWindowsSlash(keyFile);
+  this->WriteString("<None Include=\"", 2);
+  (*this->BuildFileStream) << cmVS10EscapeXML(keyFile) << "\" />\n";
+}
diff --git a/Source/cmVisualStudio10TargetGenerator.h b/Source/cmVisualStudio10TargetGenerator.h
index d72c6fd..a02dfa8 100644
--- a/Source/cmVisualStudio10TargetGenerator.h
+++ b/Source/cmVisualStudio10TargetGenerator.h
@@ -23,6 +23,7 @@
 class cmLocalVisualStudio7Generator;
 class cmComputeLinkInformation;
 class cmVisualStudioGeneratorOptions;
+struct cmIDEFlagTable;
 #include "cmSourceGroup.h"
 
 class cmVisualStudio10TargetGenerator
@@ -55,29 +56,48 @@
   void WriteString(const char* line, int indentLevel);
   void WriteProjectConfigurations();
   void WriteProjectConfigurationValues();
-  void WriteSource(const char* tool, cmSourceFile const* sf,
+  void WriteMSToolConfigurationValues(std::string const& config);
+  void WriteHeaderSource(cmSourceFile const* sf);
+  void WriteExtraSource(cmSourceFile const* sf);
+  void WriteNsightTegraConfigurationValues(std::string const& config);
+  void WriteSource(std::string const& tool, cmSourceFile const* sf,
                    const char* end = 0);
-  void WriteSources(const char* tool,
+  void WriteSources(std::string const& tool,
                     std::vector<cmSourceFile const*> const&);
   void WriteAllSources();
   void WriteDotNetReferences();
   void WriteEmbeddedResourceGroup();
   void WriteWinRTReferences();
+  void WriteWinRTPackageCertificateKeyFile();
   void WritePathAndIncrementalLinkOptions();
   void WriteItemDefinitionGroups();
+  void VerifyNecessaryFiles();
+  void WriteMissingFiles();
+  void WriteMissingFilesWP80();
+  void WriteMissingFilesWP81();
+  void WriteMissingFilesWS80();
+  void WriteMissingFilesWS81();
+  void WriteCommonMissingFiles(const std::string& manifestFile);
+  void WriteTargetSpecificReferences();
 
   bool ComputeClOptions();
   bool ComputeClOptions(std::string const& configName);
   void WriteClOptions(std::string const& config,
                       std::vector<std::string> const & includes);
+  bool ComputeRcOptions();
+  bool ComputeRcOptions(std::string const& config);
   void WriteRCOptions(std::string const& config,
                       std::vector<std::string> const & includes);
+  bool ComputeMasmOptions();
+  bool ComputeMasmOptions(std::string const& config);
+  void WriteMasmOptions(std::string const& config,
+                        std::vector<std::string> const& includes);
   bool ComputeLinkOptions();
   bool ComputeLinkOptions(std::string const& config);
   void WriteLinkOptions(std::string const& config);
   void WriteMidlOptions(std::string const& config,
                         std::vector<std::string> const & includes);
-  void OutputIncludes(std::vector<std::string> const & includes);
+  void WriteAntBuildOptions(std::string const& config);
   void OutputLinkIncremental(std::string const& configName);
   void WriteCustomRule(cmSourceFile const* source,
                        cmCustomCommand const & command);
@@ -85,8 +105,10 @@
   void WriteCustomCommand(cmSourceFile const* sf);
   void WriteGroups();
   void WriteProjectReferences();
+  void WriteApplicationTypeSettings();
   bool OutputSourceSpecificFlags(cmSourceFile const* source);
-  void AddLibraries(cmComputeLinkInformation& cli, std::string& libstring);
+  void AddLibraries(cmComputeLinkInformation& cli,
+                    std::vector<std::string>& libVec);
   void WriteLibOptions(std::string const& config);
   void WriteEvents(std::string const& configName);
   void WriteEvent(const char* name,
@@ -98,10 +120,18 @@
                               const std::vector<cmSourceGroup>& allGroups);
   bool IsResxHeader(const std::string& headerFile);
 
+  cmIDEFlagTable const* GetClFlagTable() const;
+  cmIDEFlagTable const* GetRcFlagTable() const;
+  cmIDEFlagTable const* GetLibFlagTable() const;
+  cmIDEFlagTable const* GetLinkFlagTable() const;
+  cmIDEFlagTable const* GetMasmFlagTable() const;
+
 private:
   typedef cmVisualStudioGeneratorOptions Options;
   typedef std::map<std::string, Options*> OptionsMap;
   OptionsMap ClOptions;
+  OptionsMap RcOptions;
+  OptionsMap MasmOptions;
   OptionsMap LinkOptions;
   std::string PathToVcxproj;
   cmTarget* Target;
@@ -110,10 +140,17 @@
   std::string Platform;
   std::string GUID;
   std::string Name;
+  bool MSTools;
+  bool NsightTegra;
+  int  NsightTegraVersion[4];
+  bool TargetCompileAsWinRT;
   cmGlobalVisualStudio10Generator* GlobalGenerator;
   cmGeneratedFileStream* BuildFileStream;
   cmLocalVisualStudio7Generator* LocalGenerator;
   std::set<cmSourceFile const*> SourcesVisited;
+  bool IsMissingFiles;
+  std::vector<std::string> AddedFiles;
+  std::string DefaultArtifactDir;
 
   typedef std::map<std::string, ToolSources> ToolSourceMap;
   ToolSourceMap Tools;
diff --git a/Source/cmVisualStudioGeneratorOptions.cxx b/Source/cmVisualStudioGeneratorOptions.cxx
index 81adb56..cdc8879 100644
--- a/Source/cmVisualStudioGeneratorOptions.cxx
+++ b/Source/cmVisualStudioGeneratorOptions.cxx
@@ -3,9 +3,9 @@
 #include <cmsys/System.h>
 #include "cmVisualStudio10TargetGenerator.h"
 
-inline std::string cmVisualStudio10GeneratorOptionsEscapeForXML(const char* s)
+static
+std::string cmVisualStudio10GeneratorOptionsEscapeForXML(std::string ret)
 {
-  std::string ret = s;
   cmSystemTools::ReplaceString(ret, ";", "%3B");
   cmSystemTools::ReplaceString(ret, "&", "&amp;");
   cmSystemTools::ReplaceString(ret, "<", "&lt;");
@@ -13,9 +13,9 @@
   return ret;
 }
 
-inline std::string cmVisualStudioGeneratorOptionsEscapeForXML(const char* s)
+static
+std::string cmVisualStudioGeneratorOptionsEscapeForXML(std::string ret)
 {
-  std::string ret = s;
   cmSystemTools::ReplaceString(ret, "&", "&amp;");
   cmSystemTools::ReplaceString(ret, "\"", "&quot;");
   cmSystemTools::ReplaceString(ret, "<", "&lt;");
@@ -68,6 +68,7 @@
     case cmLocalVisualStudioGenerator::VS10:
     case cmLocalVisualStudioGenerator::VS11:
     case cmLocalVisualStudioGenerator::VS12:
+    case cmLocalVisualStudioGenerator::VS14:
       // by default VS puts <ExceptionHandling></ExceptionHandling> empty
       // for a project, to make our projects look the same put a new line
       // and space over for the closing </ExceptionHandling> as the default
@@ -106,6 +107,12 @@
 }
 
 //----------------------------------------------------------------------------
+bool cmVisualStudioGeneratorOptions::IsWinRt() const
+{
+  return this->FlagMap.find("CompileAsWinRT") != this->FlagMap.end();
+}
+
+//----------------------------------------------------------------------------
 bool cmVisualStudioGeneratorOptions::UsingUnicode() const
 {
   // Look for the a _UNICODE definition.
@@ -268,7 +275,7 @@
     // Escape this flag for the IDE.
     if(this->Version >= cmLocalVisualStudioGenerator::VS10)
       {
-      define = cmVisualStudio10GeneratorOptionsEscapeForXML(define.c_str());
+      define = cmVisualStudio10GeneratorOptionsEscapeForXML(define);
 
       if(lang == "RC")
         {
@@ -277,7 +284,7 @@
       }
     else
       {
-      define = cmVisualStudioGeneratorOptionsEscapeForXML(define.c_str());
+      define = cmVisualStudioGeneratorOptionsEscapeForXML(define);
       }
     // Store the flag in the project file.
     fout << sep << define;
@@ -300,7 +307,7 @@
 {
   if(this->Version >= cmLocalVisualStudioGenerator::VS10)
     {
-    for(std::map<std::string, std::string>::iterator m = this->FlagMap.begin();
+    for(std::map<std::string, FlagValue>::iterator m = this->FlagMap.begin();
         m != this->FlagMap.end(); ++m)
       {
       fout << indent;
@@ -316,20 +323,30 @@
         {
         fout << "<" << m->first << ">";
         }
-      fout  << m->second;
-      if (m->first == "AdditionalIncludeDirectories")
+      const char* sep = "";
+      for(std::vector<std::string>::iterator i = m->second.begin();
+            i != m->second.end(); ++i)
         {
-        fout  << ";%(AdditionalIncludeDirectories)";
+        fout << sep << cmVisualStudio10GeneratorOptionsEscapeForXML(*i);
+        sep = ";";
         }
       fout  << "</" << m->first << ">\n";
       }
     }
   else
     {
-    for(std::map<std::string, std::string>::iterator m = this->FlagMap.begin();
+    for(std::map<std::string, FlagValue>::iterator m = this->FlagMap.begin();
         m != this->FlagMap.end(); ++m)
       {
-      fout << indent << m->first << "=\"" << m->second << "\"\n";
+      fout << indent << m->first << "=\"";
+      const char* sep = "";
+      for(std::vector<std::string>::iterator i = m->second.begin();
+            i != m->second.end(); ++i)
+        {
+        fout << sep << cmVisualStudioGeneratorOptionsEscapeForXML(*i);
+        sep = ";";
+        }
+      fout << "\"\n";
       }
     }
 }
@@ -358,14 +375,13 @@
         {
         fout << "<AdditionalOptions>";
         }
-      fout << this->FlagString.c_str()
+      fout << cmVisualStudio10GeneratorOptionsEscapeForXML(this->FlagString)
            << " %(AdditionalOptions)</AdditionalOptions>\n";
       }
     else
       {
       fout << prefix << "AdditionalOptions=\"";
-      fout <<
-        cmVisualStudioGeneratorOptionsEscapeForXML(this->FlagString.c_str());
+      fout << cmVisualStudioGeneratorOptionsEscapeForXML(this->FlagString);
       fout << "\"" << suffix;
       }
     }
diff --git a/Source/cmVisualStudioGeneratorOptions.h b/Source/cmVisualStudioGeneratorOptions.h
index 214b893..9951033 100644
--- a/Source/cmVisualStudioGeneratorOptions.h
+++ b/Source/cmVisualStudioGeneratorOptions.h
@@ -27,6 +27,8 @@
   enum Tool
   {
     Compiler,
+    ResourceCompiler,
+    MasmCompiler,
     Linker,
     FortranCompiler
   };
@@ -51,6 +53,7 @@
   bool UsingSBCS() const;
 
   bool IsDebug() const;
+  bool IsWinRt() const;
   // Write options to output.
   void OutputPreprocessorDefinitions(std::ostream& fout,
                                      const char* prefix,
diff --git a/Source/cmWhileCommand.cxx b/Source/cmWhileCommand.cxx
index 7d2eead..851c4cb 100644
--- a/Source/cmWhileCommand.cxx
+++ b/Source/cmWhileCommand.cxx
@@ -10,7 +10,7 @@
   See the License for more information.
 ============================================================================*/
 #include "cmWhileCommand.h"
-#include "cmIfCommand.h"
+#include "cmConditionEvaluator.h"
 
 bool cmWhileFunctionBlocker::
 IsFunctionBlocked(const cmListFileFunction& lff, cmMakefile &mf,
@@ -34,12 +34,14 @@
 
       std::string errorString;
 
-      std::vector<std::string> expandedArguments;
+      std::vector<cmExpandedCommandArgument> expandedArguments;
       mf.ExpandArguments(this->Args, expandedArguments);
       cmake::MessageType messageType;
-      bool isTrue =
-        cmIfCommand::IsTrue(expandedArguments,errorString,
-                            &mf, messageType);
+
+      cmConditionEvaluator conditionEvaluator(mf);
+
+      bool isTrue = conditionEvaluator.IsTrue(
+        expandedArguments, errorString, messageType);
 
       while (isTrue)
         {
@@ -86,9 +88,8 @@
           }
         expandedArguments.clear();
         mf.ExpandArguments(this->Args, expandedArguments);
-        isTrue =
-          cmIfCommand::IsTrue(expandedArguments,errorString,
-                              &mf, messageType);
+        isTrue = conditionEvaluator.IsTrue(
+          expandedArguments, errorString, messageType);
         }
       return true;
       }
diff --git a/Source/cmXMLParser.cxx b/Source/cmXMLParser.cxx
index a73fd70..391b874 100644
--- a/Source/cmXMLParser.cxx
+++ b/Source/cmXMLParser.cxx
@@ -20,6 +20,8 @@
 {
   this->Parser = 0;
   this->ParseError = 0;
+  this->ReportCallback = 0;
+  this->ReportCallbackData = 0;
 }
 
 //----------------------------------------------------------------------------
@@ -233,6 +235,13 @@
 //----------------------------------------------------------------------------
 void cmXMLParser::ReportError(int line, int, const char* msg)
 {
-  std::cerr << "Error parsing XML in stream at line "
-            << line << ": " << msg << std::endl;
+  if(this->ReportCallback)
+    {
+    this->ReportCallback(line, msg, this->ReportCallbackData);
+    }
+  else
+    {
+    std::cerr << "Error parsing XML in stream at line "
+              << line << ": " << msg << std::endl;
+    }
 }
diff --git a/Source/cmXMLParser.h b/Source/cmXMLParser.h
index 84a5a7d..e72da66 100644
--- a/Source/cmXMLParser.h
+++ b/Source/cmXMLParser.h
@@ -50,11 +50,18 @@
   virtual int ParseChunk(const char* inputString,
                          std::string::size_type length);
   virtual int CleanupParser();
-
+  typedef void (*ReportFunction)(int, const char*, void*);
+  void SetErrorCallback(ReportFunction f, void* d)
+    {
+      this->ReportCallback = f;
+      this->ReportCallbackData = d;
+    }
 protected:
   //! This variable is true if there was a parse error while parsing in
   //chunks.
   int ParseError;
+  ReportFunction ReportCallback;
+  void* ReportCallbackData;
 
   //1 Expat parser structure.  Exists only during call to Parse().
   void* Parser;
diff --git a/Source/cmake.cxx b/Source/cmake.cxx
index e3bebbd..09d270d 100644
--- a/Source/cmake.cxx
+++ b/Source/cmake.cxx
@@ -58,6 +58,7 @@
 #    include "cmGlobalVisualStudio10Generator.h"
 #    include "cmGlobalVisualStudio11Generator.h"
 #    include "cmGlobalVisualStudio12Generator.h"
+#    include "cmGlobalVisualStudio14Generator.h"
 #    include "cmGlobalBorlandMakefileGenerator.h"
 #    include "cmGlobalNMakeMakefileGenerator.h"
 #    include "cmGlobalJOMMakefileGenerator.h"
@@ -343,16 +344,24 @@
         // The value is transformed if it is a filepath for example, so
         // we can't compare whether the value is already in the cache until
         // after we call AddCacheEntry.
-        const char *cachedValue =
-                              this->CacheManager->GetCacheValue(var);
+        bool haveValue = false;
+        std::string cachedValue;
+        if(this->WarnUnusedCli)
+          {
+          if(const char *v = this->CacheManager->GetCacheValue(var))
+            {
+            haveValue = true;
+            cachedValue = v;
+            }
+          }
 
         this->CacheManager->AddCacheEntry(var, value.c_str(),
           "No help, variable specified on the command line.", type);
+
         if(this->WarnUnusedCli)
           {
-          if (!cachedValue
-              || strcmp(this->CacheManager->GetCacheValue(var),
-                        cachedValue) != 0)
+          if (!haveValue ||
+              cachedValue != this->CacheManager->GetCacheValue(var))
             {
             this->WatchUnusedCli(var);
             }
@@ -630,6 +639,7 @@
 {
   bool directoriesSet = directoriesSetBefore;
   bool haveToolset = false;
+  bool havePlatform = false;
   for(unsigned int i=1; i < args.size(); ++i)
     {
     std::string arg = args[i];
@@ -758,6 +768,27 @@
                    "uninitialized variables.\n";
       this->SetCheckSystemVars(true);
       }
+    else if(arg.find("-A",0) == 0)
+      {
+      std::string value = arg.substr(2);
+      if(value.size() == 0)
+        {
+        ++i;
+        if(i >= args.size())
+          {
+          cmSystemTools::Error("No platform specified for -A");
+          return;
+          }
+        value = args[i];
+        }
+      if(havePlatform)
+        {
+        cmSystemTools::Error("Multiple -A options not allowed");
+        return;
+        }
+      this->GeneratorPlatform = value;
+      havePlatform = true;
+      }
     else if(arg.find("-T",0) == 0)
       {
       std::string value = arg.substr(2);
@@ -1372,6 +1403,7 @@
         {"10.0", "Visual Studio 10 2010"},
         {"11.0", "Visual Studio 11 2012"},
         {"12.0", "Visual Studio 12 2013"},
+        {"14.0", "Visual Studio 14"},
         {0, 0}};
       for(int i=0; version[i].MSVersion != 0; i++)
         {
@@ -1435,6 +1467,34 @@
                         cmCacheManager::INTERNAL);
     }
 
+  if(const char* platformName =
+     this->CacheManager->GetCacheValue("CMAKE_GENERATOR_PLATFORM"))
+    {
+    if(this->GeneratorPlatform.empty())
+      {
+      this->GeneratorPlatform = platformName;
+      }
+    else if(this->GeneratorPlatform != platformName)
+      {
+      std::string message = "Error: generator platform: ";
+      message += this->GeneratorPlatform;
+      message += "\nDoes not match the platform used previously: ";
+      message += platformName;
+      message +=
+        "\nEither remove the CMakeCache.txt file and CMakeFiles "
+        "directory or choose a different binary directory.";
+      cmSystemTools::Error(message.c_str());
+      return -2;
+      }
+    }
+  else
+    {
+    this->CacheManager->AddCacheEntry("CMAKE_GENERATOR_PLATFORM",
+                                      this->GeneratorPlatform.c_str(),
+                                      "Name of generator platform.",
+                                      cmCacheManager::INTERNAL);
+    }
+
   if(const char* tsName =
      this->CacheManager->GetCacheValue("CMAKE_GENERATOR_TOOLSET"))
     {
@@ -1705,7 +1765,7 @@
     {
     return -1;
     }
-  this->GlobalGenerator->Generate();
+  this->GlobalGenerator->DoGenerate();
   if ( !this->GraphVizFile.empty() )
     {
     std::cout << "Generate graphviz: " << this->GraphVizFile << std::endl;
@@ -1771,6 +1831,8 @@
   this->Generators.push_back(
     cmGlobalVisualStudio12Generator::NewFactory());
   this->Generators.push_back(
+    cmGlobalVisualStudio14Generator::NewFactory());
+  this->Generators.push_back(
     cmGlobalVisualStudio71Generator::NewFactory());
   this->Generators.push_back(
     cmGlobalVisualStudio8Generator::NewFactory());
@@ -2745,7 +2807,7 @@
   projName = it.GetValue();
   return gen->Build("", dir,
                     projName, target,
-                    &output,
+                    output,
                     "",
                     config, clean, false, 0,
                     cmSystemTools::OUTPUT_PASSTHROUGH,
diff --git a/Source/cmake.h b/Source/cmake.h
index 2d04902..60ffcd4 100644
--- a/Source/cmake.h
+++ b/Source/cmake.h
@@ -191,6 +191,14 @@
   ///! Get the names of the current registered generators
   void GetRegisteredGenerators(std::vector<std::string>& names);
 
+  ///! Set the name of the selected generator-specific platform.
+  void SetGeneratorPlatform(std::string const& ts)
+    { this->GeneratorPlatform = ts; }
+
+  ///! Get the name of the selected generator-specific platform.
+  std::string const& GetGeneratorPlatform() const
+    { return this->GeneratorPlatform; }
+
   ///! Set the name of the selected generator-specific toolset.
   void SetGeneratorToolset(std::string const& ts)
     { this->GeneratorToolset = ts; }
@@ -403,6 +411,7 @@
   std::string StartOutputDirectory;
   bool SuppressDevWarnings;
   bool DoSuppressDevWarnings;
+  std::string GeneratorPlatform;
   std::string GeneratorToolset;
 
   ///! read in a cmake list file to initialize the cache
@@ -467,6 +476,7 @@
   {"-U <globbing_expr>", "Remove matching entries from CMake cache."}, \
   {"-G <generator-name>", "Specify a build system generator."},\
   {"-T <toolset-name>", "Specify toolset name if supported by generator."}, \
+  {"-A <platform-name>", "Specify platform name if supported by generator."}, \
   {"-Wno-dev", "Suppress developer warnings."},\
   {"-Wdev", "Enable developer warnings."}
 
diff --git a/Source/cmakemain.cxx b/Source/cmakemain.cxx
index 9f9f6bb..61b175e 100644
--- a/Source/cmakemain.cxx
+++ b/Source/cmakemain.cxx
@@ -42,6 +42,18 @@
   {0,
    "  cmake [options] <path-to-source>\n"
    "  cmake [options] <path-to-existing-build>"},
+  {0,
+   "Specify a source directory to (re-)generate a build system for "
+   "it in the current working directory.  Specify an existing build "
+   "directory to re-generate its build system."},
+  {0,0}
+};
+
+//----------------------------------------------------------------------------
+static const char * cmDocumentationUsageNote[][2] =
+{
+  {0,
+   "Run 'cmake --help' for more information."},
   {0,0}
 };
 
@@ -163,7 +175,7 @@
 
 int main(int ac, char const* const* av)
 {
-  setlocale(LC_ALL, "");
+  setlocale(LC_CTYPE, "");
   cmsys::Encoding::CommandLineArguments args =
     cmsys::Encoding::CommandLineArguments::Main(ac, av);
   ac = args.argc();
@@ -223,6 +235,10 @@
     doc.SetName("cmake");
     doc.SetSection("Name",cmDocumentationName);
     doc.SetSection("Usage",cmDocumentationUsage);
+    if ( ac == 1 )
+      {
+      doc.AppendSection("Usage",cmDocumentationUsageNote);
+      }
     doc.AppendSection("Generators",generators);
     doc.PrependSection("Options",cmDocumentationOptions);
 
diff --git a/Source/cmcmd.cxx b/Source/cmcmd.cxx
index 9aee975..a0c67e0 100644
--- a/Source/cmcmd.cxx
+++ b/Source/cmcmd.cxx
@@ -61,6 +61,8 @@
     << "  echo [string]...          - displays arguments as text\n"
     << "  echo_append [string]...   - displays arguments as text but no new "
        "line\n"
+    << "  env [--unset=NAME]... [NAME=VALUE]... COMMAND [ARG]...\n"
+    << "                            - run command in a modified environment\n"
     << "  environment               - display the current environment\n"
     << "  make_directory dir        - create a directory\n"
     << "  md5sum file1 [...]        - compute md5sum of files\n"
@@ -190,6 +192,55 @@
       return 0;
       }
 
+    else if (args[1] == "env" )
+      {
+      std::vector<std::string>::const_iterator ai = args.begin() + 2;
+      std::vector<std::string>::const_iterator ae = args.end();
+      for(; ai != ae; ++ai)
+        {
+        std::string const& a = *ai;
+        if(cmHasLiteralPrefix(a, "--unset="))
+          {
+          // Unset environment variable.
+          cmSystemTools::UnPutEnv(a.c_str() + 8);
+          }
+        else if(!a.empty() && a[0] == '-')
+          {
+          // Environment variable and command names cannot start in '-',
+          // so this must be an unknown option.
+          std::cerr << "cmake -E env: unknown option '" << a << "'"
+                    << std::endl;
+          return 1;
+          }
+        else if(a.find("=") != a.npos)
+          {
+          // Set environment variable.
+          cmSystemTools::PutEnv(a.c_str());
+          }
+        else
+          {
+          // This is the beginning of the command.
+          break;
+          }
+        }
+
+      if(ai == ae)
+        {
+        std::cerr << "cmake -E env: no command given" << std::endl;
+        return 1;
+        }
+
+      // Execute command from remaining arguments.
+      std::vector<std::string> cmd(ai, ae);
+      int retval;
+      if(cmSystemTools::RunSingleCommand(
+           cmd, 0, &retval, NULL, cmSystemTools::OUTPUT_PASSTHROUGH))
+        {
+        return retval;
+        }
+      return 1;
+      }
+
 #if defined(CMAKE_BUILD_WITH_CMAKE)
     // Command to create a symbolic link.  Fails on platforms not
     // supporting them.
diff --git a/Source/cmparseMSBuildXML.py b/Source/cmparseMSBuildXML.py
index d1b61ef..056a0db 100755
--- a/Source/cmparseMSBuildXML.py
+++ b/Source/cmparseMSBuildXML.py
@@ -12,6 +12,9 @@
 #  "${PROGRAMFILES}/MSBuild/Microsoft.Cpp/v4.0/v120/1033/cl.xml"
 #  "${PROGRAMFILES}/MSBuild/Microsoft.Cpp/v4.0/v120/1033/lib.xml"
 #  "${PROGRAMFILES}/MSBuild/Microsoft.Cpp/v4.0/v120/1033/link.xml"
+#  "${PROGRAMFILES}/MSBuild/Microsoft.Cpp/v4.0/V140/1033/cl.xml"
+#  "${PROGRAMFILES}/MSBuild/Microsoft.Cpp/v4.0/V140/1033/lib.xml"
+#  "${PROGRAMFILES}/MSBuild/Microsoft.Cpp/v4.0/V140/1033/link.xml"
 #
 #  BoolProperty  <Name>true|false</Name>
 #   simple example:
diff --git a/Source/ctest.cxx b/Source/ctest.cxx
index 167e348..fb97af6 100644
--- a/Source/ctest.cxx
+++ b/Source/ctest.cxx
@@ -48,7 +48,7 @@
   {"--output-on-failure", "Output anything outputted by the test program "
     "if the test should fail."},
   {"-F", "Enable failover."},
-  {"-j <jobs>, --parallel <jobs>", "Run the tests in parallel using the"
+  {"-j <jobs>, --parallel <jobs>", "Run the tests in parallel using the "
    "given number of jobs."},
   {"-Q,--quiet", "Make ctest quiet."},
   {"-O <file>, --output-log <file>", "Output to log file"},
@@ -86,6 +86,7 @@
   {"--build-two-config", "Run CMake twice"},
   {"--build-exe-dir", "Specify the directory for the executable."},
   {"--build-generator", "Specify the generator to use."},
+  {"--build-generator-platform", "Specify the generator-specific platform."},
   {"--build-generator-toolset", "Specify the generator-specific toolset."},
   {"--build-project", "Specify the name of the project to build."},
   {"--build-makeprogram", "Specify the make program to use."},
@@ -98,7 +99,7 @@
   {"--test-timeout", "The time limit in seconds, internal use only."},
   {"--tomorrow-tag", "Nightly or experimental starts with next day tag."},
   {"--ctest-config", "The configuration file used to initialize CTest state "
-  "when submitting dashboards."},
+   "when submitting dashboards."},
   {"--overwrite", "Overwrite CTest configuration option."},
   {"--extra-submit <file>[;<file>]", "Submit extra files to the dashboard."},
   {"--force-new-ctest-process", "Run child CTest instances as new processes"},
@@ -116,7 +117,7 @@
 // this is a test driver program for cmCTest.
 int main (int argc, char const* const* argv)
 {
-  setlocale(LC_ALL, "");
+  setlocale(LC_CTYPE, "");
 
   cmsys::Encoding::CommandLineArguments encoding_args =
     cmsys::Encoding::CommandLineArguments::Main(argc, argv);
diff --git a/Source/kwsys/CMakeLists.txt b/Source/kwsys/CMakeLists.txt
index 5e6a226..8ca4360 100644
--- a/Source/kwsys/CMakeLists.txt
+++ b/Source/kwsys/CMakeLists.txt
@@ -1171,10 +1171,9 @@
     ADD_EXECUTABLE(${KWSYS_NAMESPACE}TestsCxx ${KWSYS_CXX_TEST_SRCS})
     SET_PROPERTY(TARGET ${KWSYS_NAMESPACE}TestsCxx PROPERTY LABELS ${KWSYS_LABELS_EXE})
     TARGET_LINK_LIBRARIES(${KWSYS_NAMESPACE}TestsCxx ${KWSYS_NAMESPACE})
-    SET(TEST_SYSTEMTOOLS_BIN_FILE
-      "${CMAKE_CURRENT_SOURCE_DIR}/testSystemTools.bin")
-    SET(TEST_SYSTEMTOOLS_SRC_FILE
-      "${CMAKE_CURRENT_SOURCE_DIR}/testSystemTools.cxx")
+
+    SET(TEST_SYSTEMTOOLS_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}")
+    SET(TEST_SYSTEMTOOLS_BINARY_DIR "${CMAKE_CURRENT_BINARY_DIR}")
     CONFIGURE_FILE(
       ${PROJECT_SOURCE_DIR}/testSystemTools.h.in
       ${PROJECT_BINARY_DIR}/testSystemTools.h)
diff --git a/Source/kwsys/CPU.h.in b/Source/kwsys/CPU.h.in
index 2e1a584..626914b 100644
--- a/Source/kwsys/CPU.h.in
+++ b/Source/kwsys/CPU.h.in
@@ -80,6 +80,10 @@
 #elif defined(__mips) || defined(__mips__) || defined(__MIPS__)
 # define @KWSYS_NAMESPACE@_CPU_ENDIAN_ID @KWSYS_NAMESPACE@_CPU_ENDIAN_ID_BIG
 
+/* OpenRISC 1000 */
+#elif defined(__or1k__)
+# define @KWSYS_NAMESPACE@_CPU_ENDIAN_ID @KWSYS_NAMESPACE@_CPU_ENDIAN_ID_BIG
+
 /* RS/6000 */
 #elif defined(__THW_RS600) || defined(_IBMR2) || defined(_POWER)
 # define @KWSYS_NAMESPACE@_CPU_ENDIAN_ID @KWSYS_NAMESPACE@_CPU_ENDIAN_ID_BIG
diff --git a/Source/kwsys/Directory.cxx b/Source/kwsys/Directory.cxx
index d54e607..741bcba 100644
--- a/Source/kwsys/Directory.cxx
+++ b/Source/kwsys/Directory.cxx
@@ -103,7 +103,7 @@
 namespace KWSYS_NAMESPACE
 {
 
-bool Directory::Load(const char* name)
+bool Directory::Load(const kwsys_stl::string& name)
 {
   this->Clear();
 #if _MSC_VER < 1300
@@ -112,16 +112,25 @@
   intptr_t srchHandle;
 #endif
   char* buf;
-  size_t n = strlen(name);
-  if ( name[n - 1] == '/' )
+  size_t n = name.size();
+  if ( *name.rbegin() == '/' || *name.rbegin() == '\\' )
     {
     buf = new char[n + 1 + 1];
-    sprintf(buf, "%s*", name);
+    sprintf(buf, "%s*", name.c_str());
     }
   else
     {
+    // Make sure the slashes in the wildcard suffix are consistent with the
+    // rest of the path
     buf = new char[n + 2 + 1];
-    sprintf(buf, "%s/*", name);
+    if ( name.find('\\') != name.npos )
+      {
+      sprintf(buf, "%s\\*", name.c_str());
+      }
+    else
+      {
+      sprintf(buf, "%s/*", name.c_str());
+      }
     }
   struct _wfinddata_t data;      // data of current file
 
@@ -144,7 +153,7 @@
   return _findclose(srchHandle) != -1;
 }
 
-unsigned long Directory::GetNumberOfFilesInDirectory(const char* name)
+unsigned long Directory::GetNumberOfFilesInDirectory(const kwsys_stl::string& name)
 {
 #if _MSC_VER < 1300
   long srchHandle;
@@ -152,16 +161,16 @@
   intptr_t srchHandle;
 #endif
   char* buf;
-  size_t n = strlen(name);
-  if ( name[n - 1] == '/' )
+  size_t n = name.size();
+  if ( *name.rbegin() == '/' )
     {
     buf = new char[n + 1 + 1];
-    sprintf(buf, "%s*", name);
+    sprintf(buf, "%s*", name.c_str());
     }
   else
     {
     buf = new char[n + 2 + 1];
-    sprintf(buf, "%s/*", name);
+    sprintf(buf, "%s/*", name.c_str());
     }
   struct _wfinddata_t data;      // data of current file
 
@@ -206,15 +215,11 @@
 namespace KWSYS_NAMESPACE
 {
 
-bool Directory::Load(const char* name)
+bool Directory::Load(const kwsys_stl::string& name)
 {
   this->Clear();
    
-  if (!name)
-    {
-    return 0;
-    }
-  DIR* dir = opendir(name);
+  DIR* dir = opendir(name.c_str());
 
   if (!dir)
     {
@@ -230,14 +235,9 @@
   return 1;
 }
 
-unsigned long Directory::GetNumberOfFilesInDirectory(const char* name)
+unsigned long Directory::GetNumberOfFilesInDirectory(const kwsys_stl::string& name)
 {
-  DIR* dir = opendir(name);
-
-  if (!dir)
-    {
-    return 0;
-    }
+  DIR* dir = opendir(name.c_str());
 
   unsigned long count = 0;
   for (dirent* d = readdir(dir); d; d = readdir(dir) )
diff --git a/Source/kwsys/Directory.hxx.in b/Source/kwsys/Directory.hxx.in
index 05217c4..0acb191 100644
--- a/Source/kwsys/Directory.hxx.in
+++ b/Source/kwsys/Directory.hxx.in
@@ -13,6 +13,13 @@
 #define @KWSYS_NAMESPACE@_Directory_hxx
 
 #include <@KWSYS_NAMESPACE@/Configure.h>
+#include <@KWSYS_NAMESPACE@/stl/string>
+
+/* Define these macros temporarily to keep the code readable.  */
+#if !defined (KWSYS_NAMESPACE) && !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
+# define kwsys_stl @KWSYS_NAMESPACE@_stl
+# define kwsys_ios @KWSYS_NAMESPACE@_ios
+#endif
 
 namespace @KWSYS_NAMESPACE@
 {
@@ -38,7 +45,7 @@
    * in that directory. 0 is returned if the directory can not be
    * opened, 1 if it is opened.
    */
-  bool Load(const char*);
+  bool Load(const kwsys_stl::string&);
 
   /**
    * Return the number of files in the current directory.
@@ -49,7 +56,7 @@
    * Return the number of files in the specified directory.
    * A higher performance static method.
    */
-  static unsigned long GetNumberOfFilesInDirectory(const char*);
+  static unsigned long GetNumberOfFilesInDirectory(const kwsys_stl::string&);
 
   /**
    * Return the file at the given index, the indexing is 0 based
@@ -77,4 +84,10 @@
 
 } // namespace @KWSYS_NAMESPACE@
 
+/* Undefine temporary macros.  */
+#if !defined (KWSYS_NAMESPACE) && !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
+# undef kwsys_stl
+# undef kwsys_ios
+#endif
+
 #endif
diff --git a/Source/kwsys/Glob.cxx b/Source/kwsys/Glob.cxx
index 8569b0e..0916d2e 100644
--- a/Source/kwsys/Glob.cxx
+++ b/Source/kwsys/Glob.cxx
@@ -218,7 +218,7 @@
   const kwsys_stl::string& dir)
 {
   kwsys::Directory d;
-  if ( !d.Load(dir.c_str()) )
+  if ( !d.Load(dir) )
     {
     return;
     }
@@ -257,8 +257,8 @@
       fullname = dir + "/" + fname;
       }
 
-    bool isDir = kwsys::SystemTools::FileIsDirectory(realname.c_str());
-    bool isSymLink = kwsys::SystemTools::FileIsSymlink(realname.c_str());
+    bool isDir = kwsys::SystemTools::FileIsDirectory(realname);
+    bool isSymLink = kwsys::SystemTools::FileIsSymlink(realname);
 
     if ( isDir && (!isSymLink || this->RecurseThroughSymlinks) )
       {
@@ -297,7 +297,7 @@
     }
 
   kwsys::Directory d;
-  if ( !d.Load(dir.c_str()) )
+  if ( !d.Load(dir) )
     {
     return;
     }
@@ -342,12 +342,12 @@
     //kwsys_ios::cout << "Full name: " << fullname << kwsys_ios::endl;
 
     if ( !last &&
-      !kwsys::SystemTools::FileIsDirectory(realname.c_str()) )
+      !kwsys::SystemTools::FileIsDirectory(realname) )
       {
       continue;
       }
 
-    if ( this->Internals->Expressions[start].find(fname.c_str()) )
+    if ( this->Internals->Expressions[start].find(fname) )
       {
       if ( last )
         {
@@ -371,7 +371,7 @@
   this->Internals->Expressions.clear();
   this->Internals->Files.clear();
 
-  if ( !kwsys::SystemTools::FileIsFullPath(expr.c_str()) )
+  if ( !kwsys::SystemTools::FileIsFullPath(expr) )
     {
     expr = kwsys::SystemTools::GetCurrentWorkingDirectory();
     expr += "/" + inexpr;
diff --git a/Source/kwsys/ProcessUNIX.c b/Source/kwsys/ProcessUNIX.c
index 241e295..ca9d424 100644
--- a/Source/kwsys/ProcessUNIX.c
+++ b/Source/kwsys/ProcessUNIX.c
@@ -68,6 +68,7 @@
 #include <signal.h>    /* sigaction */
 #include <dirent.h>    /* DIR, dirent */
 #include <ctype.h>     /* isspace */
+#include <assert.h>    /* assert */
 
 #if defined(__VMS)
 # define KWSYSPE_VMS_NONBLOCK , O_NONBLOCK
@@ -450,6 +451,7 @@
       }
     for(i=0; i < n; ++i)
       {
+      assert(command[i]); /* Quiet Clang scan-build. */
       newCommands[cp->NumberOfCommands][i] = strdup(command[i]);
       if(!newCommands[cp->NumberOfCommands][i])
         {
diff --git a/Source/kwsys/ProcessWin32.c b/Source/kwsys/ProcessWin32.c
index c8ec754..ef71f26 100644
--- a/Source/kwsys/ProcessWin32.c
+++ b/Source/kwsys/ProcessWin32.c
@@ -36,6 +36,9 @@
 #pragma warning (push, 1)
 #endif
 #include <windows.h> /* Windows API */
+#if defined(_MSC_VER) && _MSC_VER >= 1800
+# define KWSYS_WINDOWS_DEPRECATED_GetVersionEx
+#endif
 #include <string.h>  /* strlen, strdup */
 #include <stdio.h>   /* sprintf */
 #include <io.h>      /* _unlink */
@@ -335,7 +338,14 @@
      windows.  */
   ZeroMemory(&osv, sizeof(osv));
   osv.dwOSVersionInfoSize = sizeof(osv);
+#ifdef KWSYS_WINDOWS_DEPRECATED_GetVersionEx
+# pragma warning (push)
+# pragma warning (disable:4996)
+#endif
   GetVersionEx(&osv);
+#ifdef KWSYS_WINDOWS_DEPRECATED_GetVersionEx
+# pragma warning (pop)
+#endif
   if(osv.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
     {
     /* Win9x no longer supported.  */
@@ -2370,7 +2380,14 @@
   /* Select an implementation.  */
   ZeroMemory(&osv, sizeof(osv));
   osv.dwOSVersionInfoSize = sizeof(osv);
+#ifdef KWSYS_WINDOWS_DEPRECATED_GetVersionEx
+# pragma warning (push)
+# pragma warning (disable:4996)
+#endif
   GetVersionEx(&osv);
+#ifdef KWSYS_WINDOWS_DEPRECATED_GetVersionEx
+# pragma warning (pop)
+#endif
   self->NT4 = (osv.dwPlatformId == VER_PLATFORM_WIN32_NT &&
                osv.dwMajorVersion < 5)? 1:0;
 
diff --git a/Source/kwsys/SharedForward.h.in b/Source/kwsys/SharedForward.h.in
index dd4d462..7ff29b4 100644
--- a/Source/kwsys/SharedForward.h.in
+++ b/Source/kwsys/SharedForward.h.in
@@ -512,7 +512,7 @@
   /* Invoke the child process.  */
 #if defined(_MSC_VER)
   _execvp(cmd, argv);
-#elif defined(__MINGW32__)
+#elif defined(__MINGW32__) && !defined(__MINGW64__)
   execvp(cmd, argv);
 #else
   execvp(cmd, (char* const*)argv);
diff --git a/Source/kwsys/SystemInformation.cxx b/Source/kwsys/SystemInformation.cxx
index 6544098..84b5f39 100644
--- a/Source/kwsys/SystemInformation.cxx
+++ b/Source/kwsys/SystemInformation.cxx
@@ -60,6 +60,9 @@
 
 #if defined(_WIN32)
 # include <windows.h>
+# if defined(_MSC_VER) && _MSC_VER >= 1800
+#  define KWSYS_WINDOWS_DEPRECATED_GetVersionEx
+# endif
 # include <errno.h>
 # if defined(KWSYS_SYS_HAS_PSAPI)
 #  include <psapi.h>
@@ -3696,7 +3699,10 @@
     // install ours
     struct sigaction sa;
     sa.sa_sigaction=(SigAction)StacktraceSignalHandler;
-    sa.sa_flags=SA_SIGINFO|SA_RESTART|SA_RESETHAND;
+    sa.sa_flags=SA_SIGINFO|SA_RESETHAND;
+# ifdef SA_RESTART
+    sa.sa_flags|=SA_RESTART;
+# endif
     sigemptyset(&sa.sa_mask);
 
     sigaction(SIGABRT,&sa,0);
@@ -3783,7 +3789,7 @@
     return false;
     }
 
-  if( unameInfo.release!=0 && strlen(unameInfo.release)>=3 )
+  if( strlen(unameInfo.release)>=3 )
     {
     // release looks like "2.6.3-15mdk-i686-up-4GB"
     char majorChar=unameInfo.release[0];
@@ -5060,6 +5066,10 @@
   // Try calling GetVersionEx using the OSVERSIONINFOEX structure.
   ZeroMemory (&osvi, sizeof (OSVERSIONINFOEXW));
   osvi.dwOSVersionInfoSize = sizeof (OSVERSIONINFOEXW);
+#ifdef KWSYS_WINDOWS_DEPRECATED_GetVersionEx
+# pragma warning (push)
+# pragma warning (disable:4996)
+#endif
   bOsVersionInfoEx = GetVersionExW ((OSVERSIONINFOW*)&osvi);
   if (!bOsVersionInfoEx)
     {
@@ -5069,6 +5079,9 @@
       return false;
       }
     }
+#ifdef KWSYS_WINDOWS_DEPRECATED_GetVersionEx
+# pragma warning (pop)
+#endif
 
   switch (osvi.dwPlatformId)
     {
diff --git a/Source/kwsys/SystemTools.cxx b/Source/kwsys/SystemTools.cxx
index 704cbbc..b1221e3 100644
--- a/Source/kwsys/SystemTools.cxx
+++ b/Source/kwsys/SystemTools.cxx
@@ -82,6 +82,9 @@
 # ifndef INVALID_FILE_ATTRIBUTES
 #  define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
 # endif
+# if defined(_MSC_VER) && _MSC_VER >= 1800
+#  define KWSYS_WINDOWS_DEPRECATED_GetVersionEx
+# endif
 #elif defined (__CYGWIN__)
 # include <windows.h>
 # undef _WIN32
@@ -187,17 +190,34 @@
 }
 #endif
 
+#ifdef _WIN32
+static time_t windows_filetime_to_posix_time(const FILETIME& ft)
+{
+  LARGE_INTEGER date;
+  date.HighPart = ft.dwHighDateTime;
+  date.LowPart = ft.dwLowDateTime;
+
+  // removes the diff between 1970 and 1601
+  date.QuadPart -= ((LONGLONG)(369 * 365 + 89) * 24 * 3600 * 10000000);
+
+  // converts back from 100-nanoseconds to seconds
+  return date.QuadPart / 10000000;
+}
+#endif
+
 #if defined(_WIN32) && (defined(_MSC_VER) || defined(__WATCOMC__) || defined(__BORLANDC__) || defined(__MINGW32__))
 
 #include <wctype.h>
 
-inline int Mkdir(const char* dir)
+inline int Mkdir(const kwsys_stl::string& dir)
 {
-  return _wmkdir(KWSYS_NAMESPACE::Encoding::ToWide(dir).c_str());
+  return _wmkdir(
+    KWSYS_NAMESPACE::SystemTools::ConvertToWindowsExtendedPath(dir).c_str());
 }
-inline int Rmdir(const char* dir)
+inline int Rmdir(const kwsys_stl::string& dir)
 {
-  return _wrmdir(KWSYS_NAMESPACE::Encoding::ToWide(dir).c_str());
+  return _wrmdir(
+    KWSYS_NAMESPACE::SystemTools::ConvertToWindowsExtendedPath(dir).c_str());
 }
 inline const char* Getcwd(char* buf, unsigned int len)
 {
@@ -215,15 +235,15 @@
     }
   return 0;
 }
-inline int Chdir(const char* dir)
+inline int Chdir(const kwsys_stl::string& dir)
 {
   #if defined(__BORLANDC__)
-  return chdir(dir);
+  return chdir(dir.c_str());
   #else
   return _wchdir(KWSYS_NAMESPACE::Encoding::ToWide(dir).c_str());
   #endif
 }
-inline void Realpath(const char *path, kwsys_stl::string & resolved_path)
+inline void Realpath(const kwsys_stl::string& path, kwsys_stl::string & resolved_path)
 {
   kwsys_stl::wstring tmp = KWSYS_NAMESPACE::Encoding::ToWide(path);
   wchar_t *ptemp;
@@ -243,28 +263,28 @@
 #include <sys/types.h>
 #include <fcntl.h>
 #include <unistd.h>
-inline int Mkdir(const char* dir)
+inline int Mkdir(const kwsys_stl::string& dir)
 {
-  return mkdir(dir, 00777);
+  return mkdir(dir.c_str(), 00777);
 }
-inline int Rmdir(const char* dir)
+inline int Rmdir(const kwsys_stl::string& dir)
 {
-  return rmdir(dir);
+  return rmdir(dir.c_str());
 }
 inline const char* Getcwd(char* buf, unsigned int len)
 {
   return getcwd(buf, len);
 }
 
-inline int Chdir(const char* dir)
+inline int Chdir(const kwsys_stl::string& dir)
 {
-  return chdir(dir);
+  return chdir(dir.c_str());
 }
-inline void Realpath(const char *path, kwsys_stl::string & resolved_path)
+inline void Realpath(const kwsys_stl::string& path, kwsys_stl::string & resolved_path)
 {
   char resolved_name[KWSYS_SYSTEMTOOLS_MAXPATH];
 
-  char *ret = realpath(path, resolved_name);
+  char *ret = realpath(path.c_str(), resolved_name);
   if(ret)
     {
     resolved_path = ret;
@@ -317,9 +337,9 @@
 void SystemTools::GetPath(kwsys_stl::vector<kwsys_stl::string>& path, const char* env)
 {
 #if defined(_WIN32) && !defined(__CYGWIN__)
-  const char* pathSep = ";";
+  const char pathSep = ';';
 #else
-  const char* pathSep = ":";
+  const char pathSep = ':';
 #endif
   if(!env)
     {
@@ -334,7 +354,7 @@
   kwsys_stl::string pathEnv = cpathEnv;
 
   // A hack to make the below algorithm work.
-  if(!pathEnv.empty() && pathEnv[pathEnv.length()-1] != pathSep[0])
+  if(!pathEnv.empty() && *pathEnv.rbegin() != pathSep)
     {
     pathEnv += pathSep;
     }
@@ -606,13 +626,13 @@
 #endif
 }
 
-FILE* SystemTools::Fopen(const char* file, const char* mode)
+FILE* SystemTools::Fopen(const kwsys_stl::string& file, const char* mode)
 {
 #ifdef _WIN32
-  return _wfopen(Encoding::ToWide(file).c_str(),
+  return _wfopen(SystemTools::ConvertToWindowsExtendedPath(file).c_str(),
                  Encoding::ToWide(mode).c_str());
 #else
-  return fopen(file, mode);
+  return fopen(file.c_str(), mode);
 #endif
 }
 
@@ -622,15 +642,20 @@
     {
     return false;
     }
+  return SystemTools::MakeDirectory(kwsys_stl::string(path));
+}
+
+bool SystemTools::MakeDirectory(const kwsys_stl::string& path)
+{
   if(SystemTools::FileExists(path))
     {
     return SystemTools::FileIsDirectory(path);
     }
-  kwsys_stl::string dir = path;
-  if(dir.empty())
+  if(path.empty())
     {
     return false;
     }
+  kwsys_stl::string dir = path;
   SystemTools::ConvertToUnixSlashes(dir);
 
   kwsys_stl::string::size_type pos = 0;
@@ -638,11 +663,11 @@
   while((pos = dir.find('/', pos)) != kwsys_stl::string::npos)
     {
     topdir = dir.substr(0, pos);
-    Mkdir(topdir.c_str());
+    Mkdir(topdir);
     pos++;
     }
   topdir = dir;
-  if(Mkdir(topdir.c_str()) != 0)
+  if(Mkdir(topdir) != 0)
     {
     // There is a bug in the Borland Run time library which makes MKDIR
     // return EACCES when it should return EEXISTS
@@ -1004,7 +1029,7 @@
 }
 #endif
 
-bool SystemTools::SameFile(const char* file1, const char* file2)
+bool SystemTools::SameFile(const kwsys_stl::string& file1, const kwsys_stl::string& file2)
 {
 #ifdef _WIN32
   HANDLE hFile1, hFile2;
@@ -1049,7 +1074,7 @@
            fiBuf1.nFileIndexLow == fiBuf2.nFileIndexLow);
 #else
   struct stat fileStat1, fileStat2;
-  if (stat(file1, &fileStat1) == 0 && stat(file2, &fileStat2) == 0)
+  if (stat(file1.c_str(), &fileStat1) == 0 && stat(file2.c_str(), &fileStat2) == 0)
     {
     // see if the files are the same file
     // check the device inode and size
@@ -1068,23 +1093,34 @@
 //----------------------------------------------------------------------------
 bool SystemTools::FileExists(const char* filename)
 {
-  if(!(filename && *filename))
+  if(!filename)
+    {
+    return false;
+    }
+  return SystemTools::FileExists(kwsys_stl::string(filename));
+}
+
+//----------------------------------------------------------------------------
+bool SystemTools::FileExists(const kwsys_stl::string& filename)
+{
+  if(filename.empty())
     {
     return false;
     }
 #if defined(__CYGWIN__)
   // Convert filename to native windows path if possible.
   char winpath[MAX_PATH];
-  if(SystemTools::PathCygwinToWin32(filename, winpath))
+  if(SystemTools::PathCygwinToWin32(filename.c_str(), winpath))
     {
     return (GetFileAttributesA(winpath) != INVALID_FILE_ATTRIBUTES);
     }
-  return access(filename, R_OK) == 0;
+  return access(filename.c_str(), R_OK) == 0;
 #elif defined(_WIN32)
-  return (GetFileAttributesW(Encoding::ToWide(filename).c_str())
+  return (GetFileAttributesW(
+            SystemTools::ConvertToWindowsExtendedPath(filename).c_str())
           != INVALID_FILE_ATTRIBUTES);
 #else
-  return access(filename, R_OK) == 0;
+  return access(filename.c_str(), R_OK) == 0;
 #endif
 }
 
@@ -1101,6 +1137,18 @@
 }
 
 //----------------------------------------------------------------------------
+bool SystemTools::FileExists(const kwsys_stl::string& filename, bool isFile)
+{
+  if(SystemTools::FileExists(filename))
+    {
+    // If isFile is set return not FileIsDirectory,
+    // so this will only be true if it is a file
+    return !isFile || !SystemTools::FileIsDirectory(filename);
+    }
+  return false;
+}
+
+//----------------------------------------------------------------------------
 #ifdef __CYGWIN__
 bool SystemTools::PathCygwinToWin32(const char *path, char *win32_path)
 {
@@ -1124,7 +1172,7 @@
 }
 #endif
 
-bool SystemTools::Touch(const char* filename, bool create)
+bool SystemTools::Touch(const kwsys_stl::string& filename, bool create)
 {
   if(create && !SystemTools::FileExists(filename))
     {
@@ -1137,10 +1185,11 @@
     return false;
     }
 #if defined(_WIN32) && !defined(__CYGWIN__)
-  HANDLE h = CreateFileW(Encoding::ToWide(filename).c_str(),
-                        FILE_WRITE_ATTRIBUTES,
-                        FILE_SHARE_WRITE, 0, OPEN_EXISTING,
-                        FILE_FLAG_BACKUP_SEMANTICS, 0);
+  HANDLE h = CreateFileW(
+    SystemTools::ConvertToWindowsExtendedPath(filename).c_str(),
+    FILE_WRITE_ATTRIBUTES,
+    FILE_SHARE_WRITE, 0, OPEN_EXISTING,
+    FILE_FLAG_BACKUP_SEMANTICS, 0);
   if(!h)
     {
     return false;
@@ -1155,13 +1204,13 @@
   CloseHandle(h);
 #elif KWSYS_CXX_HAS_UTIMENSAT
   struct timespec times[2] = {{0,UTIME_OMIT},{0,UTIME_NOW}};
-  if(utimensat(AT_FDCWD, filename, times, 0) < 0)
+  if(utimensat(AT_FDCWD, filename.c_str(), times, 0) < 0)
     {
     return false;
     }
 #else
   struct stat st;
-  if(stat(filename, &st) < 0)
+  if(stat(filename.c_str(), &st) < 0)
     {
     return false;
     }
@@ -1177,13 +1226,13 @@
 #  endif
       mtime
     };
-  if(utimes(filename, times) < 0)
+  if(utimes(filename.c_str(), times) < 0)
     {
     return false;
     }
 # else
   struct utimbuf times = {st.st_atime, mtime.tv_sec};
-  if(utime(filename, &times) < 0)
+  if(utime(filename.c_str(), &times) < 0)
     {
     return false;
     }
@@ -1192,7 +1241,8 @@
   return true;
 }
 
-bool SystemTools::FileTimeCompare(const char* f1, const char* f2,
+bool SystemTools::FileTimeCompare(const kwsys_stl::string& f1,
+                                  const kwsys_stl::string& f2,
                                   int* result)
 {
   // Default to same time.
@@ -1200,12 +1250,12 @@
 #if !defined(_WIN32) || defined(__CYGWIN__)
   // POSIX version.  Use stat function to get file modification time.
   struct stat s1;
-  if(stat(f1, &s1) != 0)
+  if(stat(f1.c_str(), &s1) != 0)
     {
     return false;
     }
   struct stat s2;
-  if(stat(f2, &s2) != 0)
+  if(stat(f2.c_str(), &s2) != 0)
     {
     return false;
     }
@@ -1242,13 +1292,15 @@
   // Windows version.  Get the modification time from extended file attributes.
   WIN32_FILE_ATTRIBUTE_DATA f1d;
   WIN32_FILE_ATTRIBUTE_DATA f2d;
-  if(!GetFileAttributesExW(Encoding::ToWide(f1).c_str(),
-                           GetFileExInfoStandard, &f1d))
+  if(!GetFileAttributesExW(
+       SystemTools::ConvertToWindowsExtendedPath(f1).c_str(),
+       GetFileExInfoStandard, &f1d))
     {
     return false;
     }
-  if(!GetFileAttributesExW(Encoding::ToWide(f2).c_str(),
-                           GetFileExInfoStandard, &f2d))
+  if(!GetFileAttributesExW(
+       SystemTools::ConvertToWindowsExtendedPath(f2).c_str(),
+       GetFileExInfoStandard, &f2d))
     {
     return false;
     }
@@ -1514,6 +1566,17 @@
   return len1 >= len2 && !strncmp(str1, str2, len2) ? true : false;
 }
 
+// Returns if string starts with another string
+bool SystemTools::StringStartsWith(const kwsys_stl::string& str1, const char* str2)
+{
+  if (!str2)
+    {
+    return false;
+    }
+  size_t len1 = str1.size(), len2 = strlen(str2);
+  return len1 >= len2 && !strncmp(str1.c_str(), str2, len2) ? true : false;
+}
+
 // Returns if string ends with another string
 bool SystemTools::StringEndsWith(const char* str1, const char* str2)
 {
@@ -1525,6 +1588,17 @@
   return len1 >= len2 &&  !strncmp(str1 + (len1 - len2), str2, len2) ? true : false;
 }
 
+// Returns if string ends with another string
+bool SystemTools::StringEndsWith(const kwsys_stl::string& str1, const char* str2)
+{
+  if (!str2)
+    {
+    return false;
+    }
+  size_t len1 = str1.size(), len2 = strlen(str2);
+  return len1 >= len2 &&  !strncmp(str1.c_str() + (len1 - len2), str2, len2) ? true : false;
+}
+
 // Returns a pointer to the last occurence of str2 in str1
 const char* SystemTools::FindLastString(const char* str1, const char* str2)
 {
@@ -1594,7 +1668,7 @@
 }
 
 //----------------------------------------------------------------------------
-kwsys_stl::vector<kwsys::String> SystemTools::SplitString(const char* p, char sep, bool isPath)
+kwsys_stl::vector<kwsys::String> SystemTools::SplitString(const kwsys_stl::string& p, char sep, bool isPath)
 {
   kwsys_stl::string path = p;
   kwsys_stl::vector<kwsys::String> paths;
@@ -1830,8 +1904,73 @@
     }
 }
 
+#ifdef _WIN32
+// Convert local paths to UNC style paths
+kwsys_stl::wstring
+SystemTools::ConvertToWindowsExtendedPath(const kwsys_stl::string &source)
+{
+  kwsys_stl::wstring wsource = Encoding::ToWide(source);
+
+  // Resolve any relative paths
+  DWORD wfull_len;
+
+  /* The +3 is a workaround for a bug in some versions of GetFullPathNameW that
+   * won't return a large enough buffer size if the input is too small */
+  wfull_len = GetFullPathNameW(wsource.c_str(), 0, NULL, NULL) + 3;
+  kwsys_stl::vector<wchar_t> wfull(wfull_len);
+  GetFullPathNameW(wsource.c_str(), wfull_len, &wfull[0], NULL);
+
+  /* This should get the correct size without any extra padding from the
+   * previous size workaround. */
+  wfull_len = static_cast<DWORD>(wcslen(&wfull[0]));
+
+  if(wfull_len >= 2 && isalpha(wfull[0]) && wfull[1] == L':')
+    { /* C:\Foo\bar\FooBar.txt */
+    return L"\\\\?\\" + kwsys_stl::wstring(&wfull[0]);
+    }
+  else if(wfull_len >= 2 && wfull[0] == L'\\' && wfull[1] == L'\\')
+    { /* Starts with \\ */
+    if(wfull_len >= 4 && wfull[2] == L'?' && wfull[3] == L'\\')
+      { /* Starts with \\?\ */
+      if(wfull_len >= 8 && wfull[4] == L'U' && wfull[5] == L'N' &&
+                           wfull[6] == L'C' && wfull[7] == L'\\')
+        { /* \\?\UNC\Foo\bar\FooBar.txt */
+        return kwsys_stl::wstring(&wfull[0]);
+        }
+      else if(wfull_len >= 6 && isalpha(wfull[4]) && wfull[5] == L':')
+        { /* \\?\C:\Foo\bar\FooBar.txt */
+        return kwsys_stl::wstring(&wfull[0]);
+        }
+      else if(wfull_len >= 5)
+        { /* \\?\Foo\bar\FooBar.txt */
+        return L"\\\\?\\UNC\\" + kwsys_stl::wstring(&wfull[4]);
+        }
+      }
+    else if(wfull_len >= 4 && wfull[2] == L'.' && wfull[3] == L'\\')
+      { /* Starts with \\.\ a device name */
+      if(wfull_len >= 6 && isalpha(wfull[4]) && wfull[5] == L':')
+        { /* \\.\C:\Foo\bar\FooBar.txt */
+        return L"\\\\?\\" + kwsys_stl::wstring(&wfull[4]);
+        }
+      else if(wfull_len >= 5)
+        { /* \\.\Foo\bar\ Device name is left unchanged */
+        return kwsys_stl::wstring(&wfull[0]);
+        }
+      }
+    else if(wfull_len >= 3)
+      { /* \\Foo\bar\FooBar.txt */
+      return L"\\\\?\\UNC\\" + kwsys_stl::wstring(&wfull[2]);
+      }
+    }
+
+  // If this case has been reached, then the path is invalid.  Leave it
+  // unchanged
+  return Encoding::ToWide(source);
+}
+#endif
+
 // change // to /, and escape any spaces in the path
-kwsys_stl::string SystemTools::ConvertToUnixOutputPath(const char* path)
+kwsys_stl::string SystemTools::ConvertToUnixOutputPath(const kwsys_stl::string& path)
 {
   kwsys_stl::string ret = path;
 
@@ -1861,7 +2000,7 @@
   return ret;
 }
 
-kwsys_stl::string SystemTools::ConvertToOutputPath(const char* path)
+kwsys_stl::string SystemTools::ConvertToOutputPath(const kwsys_stl::string& path)
 {
 #if defined(_WIN32) && !defined(__CYGWIN__)
   return SystemTools::ConvertToWindowsOutputPath(path);
@@ -1871,13 +2010,12 @@
 }
 
 // remove double slashes not at the start
-kwsys_stl::string SystemTools::ConvertToWindowsOutputPath(const char* path)
+kwsys_stl::string SystemTools::ConvertToWindowsOutputPath(const kwsys_stl::string& path)
 {
   kwsys_stl::string ret;
   // make it big enough for all of path and double quotes
-  ret.reserve(strlen(path)+3);
+  ret.reserve(path.size()+3);
   // put path into the string
-  ret.assign(path);
   ret = path;
   kwsys_stl::string::size_type pos = 0;
   // first convert all of the slashes
@@ -1919,8 +2057,8 @@
   return ret;
 }
 
-bool SystemTools::CopyFileIfDifferent(const char* source,
-                                      const char* destination)
+bool SystemTools::CopyFileIfDifferent(const kwsys_stl::string& source,
+                                      const kwsys_stl::string& destination)
 {
   // special check for a destination that is a directory
   // FilesDiffer does not handle file to directory compare
@@ -1931,7 +2069,7 @@
     new_destination += '/';
     kwsys_stl::string source_name = source;
     new_destination += SystemTools::GetFilenameName(source_name);
-    if(SystemTools::FilesDiffer(source, new_destination.c_str()))
+    if(SystemTools::FilesDiffer(source, new_destination))
       {
       return SystemTools::CopyFileAlways(source, destination);
       }
@@ -1954,23 +2092,25 @@
 
 #define KWSYS_ST_BUFFER 4096
 
-bool SystemTools::FilesDiffer(const char* source,
-                              const char* destination)
+bool SystemTools::FilesDiffer(const kwsys_stl::string& source,
+                              const kwsys_stl::string& destination)
 {
 
 #if defined(_WIN32)
   WIN32_FILE_ATTRIBUTE_DATA statSource;
-  if (GetFileAttributesExW(Encoding::ToWide(source).c_str(),
-                           GetFileExInfoStandard,
-                           &statSource) == 0)
+  if (GetFileAttributesExW(
+        SystemTools::ConvertToWindowsExtendedPath(source).c_str(),
+        GetFileExInfoStandard,
+        &statSource) == 0)
     {
     return true;
     }
 
   WIN32_FILE_ATTRIBUTE_DATA statDestination;
-  if (GetFileAttributesExW(Encoding::ToWide(destination).c_str(),
-                           GetFileExInfoStandard,
-                           &statDestination) == 0)
+  if (GetFileAttributesExW(
+        SystemTools::ConvertToWindowsExtendedPath(destination).c_str(),
+        GetFileExInfoStandard,
+        &statDestination) == 0)
     {
     return true;
     }
@@ -1991,13 +2131,13 @@
 #else
 
   struct stat statSource;
-  if (stat(source, &statSource) != 0)
+  if (stat(source.c_str(), &statSource) != 0)
     {
     return true;
     }
 
   struct stat statDestination;
-  if (stat(destination, &statDestination) != 0)
+  if (stat(destination.c_str(), &statDestination) != 0)
     {
     return true;
     }
@@ -2015,15 +2155,15 @@
 #endif
 
 #if defined(_WIN32)
-  kwsys::ifstream finSource(source,
+  kwsys::ifstream finSource(source.c_str(),
                             (kwsys_ios::ios::binary |
                              kwsys_ios::ios::in));
-  kwsys::ifstream finDestination(destination,
+  kwsys::ifstream finDestination(destination.c_str(),
                                  (kwsys_ios::ios::binary |
                                   kwsys_ios::ios::in));
 #else
-  kwsys::ifstream finSource(source);
-  kwsys::ifstream finDestination(destination);
+  kwsys::ifstream finSource(source.c_str());
+  kwsys::ifstream finDestination(destination.c_str());
 #endif
   if(!finSource || !finDestination)
     {
@@ -2068,7 +2208,7 @@
 /**
  * Copy a file named by "source" to the file named by "destination".
  */
-bool SystemTools::CopyFileAlways(const char* source, const char* destination)
+bool SystemTools::CopyFileAlways(const kwsys_stl::string& source, const kwsys_stl::string& destination)
 {
   // If files are the same do not copy
   if ( SystemTools::SameFile(source, destination) )
@@ -2084,31 +2224,33 @@
   // If destination is a directory, try to create a file with the same
   // name as the source in that directory.
 
-  kwsys_stl::string new_destination;
+  kwsys_stl::string real_destination = destination;
+  kwsys_stl::string destination_dir;
   if(SystemTools::FileExists(destination) &&
      SystemTools::FileIsDirectory(destination))
     {
-    new_destination = destination;
-    SystemTools::ConvertToUnixSlashes(new_destination);
-    new_destination += '/';
+    destination_dir = real_destination;
+    SystemTools::ConvertToUnixSlashes(real_destination);
+    real_destination += '/';
     kwsys_stl::string source_name = source;
-    new_destination += SystemTools::GetFilenameName(source_name);
-    destination = new_destination.c_str();
+    real_destination += SystemTools::GetFilenameName(source_name);
+    }
+  else
+    {
+    destination_dir = SystemTools::GetFilenamePath(destination);
     }
 
   // Create destination directory
 
-  kwsys_stl::string destination_dir = destination;
-  destination_dir = SystemTools::GetFilenamePath(destination_dir);
-  SystemTools::MakeDirectory(destination_dir.c_str());
+  SystemTools::MakeDirectory(destination_dir);
 
   // Open files
 
 #if defined(_WIN32) || defined(__CYGWIN__)
-  kwsys::ifstream fin(source,
+  kwsys::ifstream fin(source.c_str(),
                 kwsys_ios::ios::binary | kwsys_ios::ios::in);
 #else
-  kwsys::ifstream fin(source);
+  kwsys::ifstream fin(source.c_str());
 #endif
   if(!fin)
     {
@@ -2119,13 +2261,13 @@
   // 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);
+  SystemTools::RemoveFile(real_destination);
 
 #if defined(_WIN32) || defined(__CYGWIN__)
-  kwsys::ofstream fout(destination,
+  kwsys::ofstream fout(real_destination.c_str(),
                      kwsys_ios::ios::binary | kwsys_ios::ios::out | kwsys_ios::ios::trunc);
 #else
-  kwsys::ofstream fout(destination,
+  kwsys::ofstream fout(real_destination.c_str(),
                      kwsys_ios::ios::out | kwsys_ios::ios::trunc);
 #endif
   if(!fout)
@@ -2161,7 +2303,7 @@
     }
   if ( perms )
     {
-    if ( !SystemTools::SetPermissions(destination, perm) )
+    if ( !SystemTools::SetPermissions(real_destination, perm) )
       {
       return false;
       }
@@ -2170,7 +2312,7 @@
 }
 
 //----------------------------------------------------------------------------
-bool SystemTools::CopyAFile(const char* source, const char* destination,
+bool SystemTools::CopyAFile(const kwsys_stl::string& source, const kwsys_stl::string& destination,
                             bool always)
 {
   if(always)
@@ -2187,11 +2329,16 @@
  * Copy a directory content from "source" directory to the directory named by
  * "destination".
  */
-bool SystemTools::CopyADirectory(const char* source, const char* destination,
+bool SystemTools::CopyADirectory(const kwsys_stl::string& source, const kwsys_stl::string& destination,
                                  bool always)
 {
   Directory dir;
+#ifdef _WIN32
+  dir.Load(Encoding::ToNarrow(
+             SystemTools::ConvertToWindowsExtendedPath(source)));
+#else
   dir.Load(source);
+#endif
   size_t fileNum;
   if ( !SystemTools::MakeDirectory(destination) )
     {
@@ -2205,13 +2352,13 @@
       kwsys_stl::string fullPath = source;
       fullPath += "/";
       fullPath += dir.GetFile(static_cast<unsigned long>(fileNum));
-      if(SystemTools::FileIsDirectory(fullPath.c_str()))
+      if(SystemTools::FileIsDirectory(fullPath))
         {
         kwsys_stl::string fullDestPath = destination;
         fullDestPath += "/";
         fullDestPath += dir.GetFile(static_cast<unsigned long>(fileNum));
-        if (!SystemTools::CopyADirectory(fullPath.c_str(),
-                                         fullDestPath.c_str(),
+        if (!SystemTools::CopyADirectory(fullPath,
+                                         fullDestPath,
                                          always))
           {
           return false;
@@ -2219,7 +2366,7 @@
         }
       else
         {
-        if(!SystemTools::CopyAFile(fullPath.c_str(), destination, always))
+        if(!SystemTools::CopyAFile(fullPath, destination, always))
           {
           return false;
           }
@@ -2234,15 +2381,28 @@
 // return size of file; also returns zero if no file exists
 unsigned long SystemTools::FileLength(const char* filename)
 {
+  unsigned long length = 0;
+#ifdef _WIN32
+  WIN32_FILE_ATTRIBUTE_DATA fs;
+  if (GetFileAttributesExW(
+        SystemTools::ConvertToWindowsExtendedPath(filename).c_str(),
+        GetFileExInfoStandard, &fs) != 0)
+    {
+    /* To support the full 64-bit file size, use fs.nFileSizeHigh
+     * and fs.nFileSizeLow to construct the 64 bit size
+
+    length = ((__int64)fs.nFileSizeHigh << 32) + fs.nFileSizeLow;
+     */
+    length = static_cast<unsigned long>(fs.nFileSizeLow);
+    }
+#else
   struct stat fs;
-  if (stat(filename, &fs) != 0)
+  if (stat(filename, &fs) == 0)
     {
-      return 0;
+    length = static_cast<unsigned long>(fs.st_size);
     }
-  else
-    {
-      return static_cast<unsigned long>(fs.st_size);
-    }
+#endif
+  return length;
 }
 
 int SystemTools::Strucmp(const char *s1, const char *s2)
@@ -2259,31 +2419,49 @@
 }
 
 // return file's modified time
-long int SystemTools::ModifiedTime(const char* filename)
+long int SystemTools::ModifiedTime(const kwsys_stl::string& filename)
 {
+  long int mt = 0;
+#ifdef _WIN32
+  WIN32_FILE_ATTRIBUTE_DATA fs;
+  if (GetFileAttributesExW(
+        SystemTools::ConvertToWindowsExtendedPath(filename).c_str(),
+                           GetFileExInfoStandard,
+                           &fs) != 0)
+    {
+    mt = windows_filetime_to_posix_time(fs.ftLastWriteTime);
+    }
+#else
   struct stat fs;
-  if (stat(filename, &fs) != 0)
+  if (stat(filename.c_str(), &fs) == 0)
     {
-    return 0;
+    mt = static_cast<long int>(fs.st_mtime);
     }
-  else
-    {
-    return static_cast<long int>(fs.st_mtime);
-    }
+#endif
+  return mt;
 }
 
 // return file's creation time
-long int SystemTools::CreationTime(const char* filename)
+long int SystemTools::CreationTime(const kwsys_stl::string& filename)
 {
+  long int ct = 0;
+#ifdef _WIN32
+  WIN32_FILE_ATTRIBUTE_DATA fs;
+  if (GetFileAttributesExW(
+        SystemTools::ConvertToWindowsExtendedPath(filename).c_str(),
+                           GetFileExInfoStandard,
+                           &fs) != 0)
+    {
+    ct = windows_filetime_to_posix_time(fs.ftCreationTime);
+    }
+#else
   struct stat fs;
-  if (stat(filename, &fs) != 0)
+  if (stat(filename.c_str(), &fs) == 0)
     {
-    return 0;
+    ct = fs.st_ctime >= 0 ? static_cast<long int>(fs.st_ctime) : 0;
     }
-  else
-    {
-    return fs.st_ctime >= 0 ? static_cast<long int>(fs.st_ctime) : 0;
-    }
+#endif
+  return ct;
 }
 
 bool SystemTools::ConvertDateMacroString(const char *str, time_t *tmt)
@@ -2394,7 +2572,7 @@
   return strerror(e);
 }
 
-bool SystemTools::RemoveFile(const char* source)
+bool SystemTools::RemoveFile(const kwsys_stl::string& source)
 {
 #ifdef _WIN32
   mode_t mode;
@@ -2406,9 +2584,10 @@
   SystemTools::SetPermissions(source, S_IWRITE);
 #endif
 #ifdef _WIN32
-  bool res = _wunlink(Encoding::ToWide(source).c_str()) != 0 ? false : true;
+  bool res =
+    _wunlink(SystemTools::ConvertToWindowsExtendedPath(source).c_str()) == 0;
 #else
-  bool res = unlink(source) != 0 ? false : true;
+  bool res = unlink(source.c_str()) != 0 ? false : true;
 #endif
 #ifdef _WIN32
   if ( !res )
@@ -2419,7 +2598,7 @@
   return res;
 }
 
-bool SystemTools::RemoveADirectory(const char* source)
+bool SystemTools::RemoveADirectory(const kwsys_stl::string& source)
 {
   // Add write permission to the directory so we can modify its
   // content to remove files and directories from it.
@@ -2435,7 +2614,12 @@
     }
 
   Directory dir;
+#ifdef _WIN32
+  dir.Load(Encoding::ToNarrow(
+             SystemTools::ConvertToWindowsExtendedPath(source)));
+#else
   dir.Load(source);
+#endif
   size_t fileNum;
   for (fileNum = 0; fileNum <  dir.GetNumberOfFiles(); ++fileNum)
     {
@@ -2445,17 +2629,17 @@
       kwsys_stl::string fullPath = source;
       fullPath += "/";
       fullPath += dir.GetFile(static_cast<unsigned long>(fileNum));
-      if(SystemTools::FileIsDirectory(fullPath.c_str()) &&
-        !SystemTools::FileIsSymlink(fullPath.c_str()))
+      if(SystemTools::FileIsDirectory(fullPath) &&
+        !SystemTools::FileIsSymlink(fullPath))
         {
-        if (!SystemTools::RemoveADirectory(fullPath.c_str()))
+        if (!SystemTools::RemoveADirectory(fullPath))
           {
           return false;
           }
         }
       else
         {
-        if(!SystemTools::RemoveFile(fullPath.c_str()))
+        if(!SystemTools::RemoveFile(fullPath))
           {
           return false;
           }
@@ -2517,7 +2701,7 @@
     {
     tryPath = *p;
     tryPath += name;
-    if(SystemTools::FileExists(tryPath.c_str()))
+    if(SystemTools::FileExists(tryPath))
       {
       return tryPath;
       }
@@ -2537,7 +2721,7 @@
            bool no_system_path)
 {
   kwsys_stl::string tryPath = SystemTools::FindName(name, userPaths, no_system_path);
-  if(tryPath != "" && !SystemTools::FileIsDirectory(tryPath.c_str()))
+  if(!tryPath.empty() && !SystemTools::FileIsDirectory(tryPath))
     {
     return SystemTools::CollapseFullPath(tryPath);
     }
@@ -2556,7 +2740,7 @@
                 bool no_system_path)
 {
   kwsys_stl::string tryPath = SystemTools::FindName(name, userPaths, no_system_path);
-  if(tryPath != "" && SystemTools::FileIsDirectory(tryPath.c_str()))
+  if(!tryPath.empty() && SystemTools::FileIsDirectory(tryPath))
     {
     return SystemTools::CollapseFullPath(tryPath);
     }
@@ -2578,7 +2762,14 @@
     {
     return "";
     }
-  kwsys_stl::string name = nameIn;
+  return SystemTools::FindProgram(kwsys_stl::string(nameIn), userPaths, no_system_path);
+}
+
+kwsys_stl::string SystemTools::FindProgram(
+  const kwsys_stl::string& name,
+  const kwsys_stl::vector<kwsys_stl::string>& userPaths,
+  bool no_system_path)
+{
   kwsys_stl::vector<kwsys_stl::string> extensions;
 #if defined (_WIN32) || defined(__CYGWIN__) || defined(__MINGW32__)
   bool hasExtension = false;
@@ -2603,16 +2794,16 @@
     {
     tryPath = name;
     tryPath += *i;
-    if(SystemTools::FileExists(tryPath.c_str()) &&
-        !SystemTools::FileIsDirectory(tryPath.c_str()))
+    if(SystemTools::FileExists(tryPath) &&
+        !SystemTools::FileIsDirectory(tryPath))
       {
       return SystemTools::CollapseFullPath(tryPath);
       }
     }
   // now try just the name
   tryPath = name;
-  if(SystemTools::FileExists(tryPath.c_str()) &&
-     !SystemTools::FileIsDirectory(tryPath.c_str()))
+  if(SystemTools::FileExists(tryPath) &&
+     !SystemTools::FileIsDirectory(tryPath))
     {
     return SystemTools::CollapseFullPath(tryPath);
     }
@@ -2658,8 +2849,8 @@
       tryPath = *p;
       tryPath += name;
       tryPath += *ext;
-      if(SystemTools::FileExists(tryPath.c_str()) &&
-          !SystemTools::FileIsDirectory(tryPath.c_str()))
+      if(SystemTools::FileExists(tryPath) &&
+          !SystemTools::FileIsDirectory(tryPath))
         {
         return SystemTools::CollapseFullPath(tryPath);
         }
@@ -2667,8 +2858,8 @@
     // now try it without them
     tryPath = *p;
     tryPath += name;
-    if(SystemTools::FileExists(tryPath.c_str()) &&
-       !SystemTools::FileIsDirectory(tryPath.c_str()))
+    if(SystemTools::FileExists(tryPath) &&
+       !SystemTools::FileIsDirectory(tryPath))
       {
       return SystemTools::CollapseFullPath(tryPath);
       }
@@ -2686,7 +2877,7 @@
       it != names.end() ; ++it)
     {
     // Try to find the program.
-    kwsys_stl::string result = SystemTools::FindProgram(it->c_str(),
+    kwsys_stl::string result = SystemTools::FindProgram(*it,
                                                   path,
                                                   noSystemPath);
     if ( !result.empty() )
@@ -2703,7 +2894,7 @@
  * found.  Otherwise, the empty string is returned.
  */
 kwsys_stl::string SystemTools
-::FindLibrary(const char* name,
+::FindLibrary(const kwsys_stl::string& name,
               const kwsys_stl::vector<kwsys_stl::string>& userPaths)
 {
   // See if the executable exists as written.
@@ -2744,8 +2935,8 @@
     tryPath = *p;
     tryPath += name;
     tryPath += ".framework";
-    if(SystemTools::FileExists(tryPath.c_str())
-       && SystemTools::FileIsDirectory(tryPath.c_str()))
+    if(SystemTools::FileExists(tryPath)
+       && SystemTools::FileIsDirectory(tryPath))
       {
       return SystemTools::CollapseFullPath(tryPath);
       }
@@ -2754,8 +2945,8 @@
     tryPath = *p;
     tryPath += name;
     tryPath += ".lib";
-    if(SystemTools::FileExists(tryPath.c_str())
-       && !SystemTools::FileIsDirectory(tryPath.c_str()))
+    if(SystemTools::FileExists(tryPath)
+       && !SystemTools::FileIsDirectory(tryPath))
       {
       return SystemTools::CollapseFullPath(tryPath);
       }
@@ -2764,8 +2955,8 @@
     tryPath += "lib";
     tryPath += name;
     tryPath += ".so";
-    if(SystemTools::FileExists(tryPath.c_str())
-       && !SystemTools::FileIsDirectory(tryPath.c_str()))
+    if(SystemTools::FileExists(tryPath)
+       && !SystemTools::FileIsDirectory(tryPath))
       {
       return SystemTools::CollapseFullPath(tryPath);
       }
@@ -2773,8 +2964,8 @@
     tryPath += "lib";
     tryPath += name;
     tryPath += ".a";
-    if(SystemTools::FileExists(tryPath.c_str())
-       && !SystemTools::FileIsDirectory(tryPath.c_str()))
+    if(SystemTools::FileExists(tryPath)
+       && !SystemTools::FileIsDirectory(tryPath))
       {
       return SystemTools::CollapseFullPath(tryPath);
       }
@@ -2782,8 +2973,8 @@
     tryPath += "lib";
     tryPath += name;
     tryPath += ".sl";
-    if(SystemTools::FileExists(tryPath.c_str())
-       && !SystemTools::FileIsDirectory(tryPath.c_str()))
+    if(SystemTools::FileExists(tryPath)
+       && !SystemTools::FileIsDirectory(tryPath))
       {
       return SystemTools::CollapseFullPath(tryPath);
       }
@@ -2791,8 +2982,8 @@
     tryPath += "lib";
     tryPath += name;
     tryPath += ".dylib";
-    if(SystemTools::FileExists(tryPath.c_str())
-       && !SystemTools::FileIsDirectory(tryPath.c_str()))
+    if(SystemTools::FileExists(tryPath)
+       && !SystemTools::FileIsDirectory(tryPath))
       {
       return SystemTools::CollapseFullPath(tryPath);
       }
@@ -2800,8 +2991,8 @@
     tryPath += "lib";
     tryPath += name;
     tryPath += ".dll";
-    if(SystemTools::FileExists(tryPath.c_str())
-       && !SystemTools::FileIsDirectory(tryPath.c_str()))
+    if(SystemTools::FileExists(tryPath)
+       && !SystemTools::FileIsDirectory(tryPath))
       {
       return SystemTools::CollapseFullPath(tryPath);
       }
@@ -2812,32 +3003,33 @@
   return "";
 }
 
-kwsys_stl::string SystemTools::GetRealPath(const char* path)
+kwsys_stl::string SystemTools::GetRealPath(const kwsys_stl::string& path)
 {
   kwsys_stl::string ret;
   Realpath(path, ret);
   return ret;
 }
 
-bool SystemTools::FileIsDirectory(const char* name)
+bool SystemTools::FileIsDirectory(const kwsys_stl::string& inName)
 {
-  if (!*name)
+  if (inName.empty())
     {
     return false;
     }
-  size_t length = strlen(name);
+  size_t length = inName.size();
+  const char* name = inName.c_str();
 
   // Remove any trailing slash from the name except in a root component.
   char local_buffer[KWSYS_SYSTEMTOOLS_MAXPATH];
   std::string string_buffer;
   size_t last = length-1;
   if(last > 0 && (name[last] == '/' || name[last] == '\\')
-    && strcmp(name, "/") !=0 && name[last-1] != ':')
+    && strcmp(name, "/") != 0 && name[last-1] != ':')
     {
-    if(last < sizeof(local_buffer))
+    if (last < sizeof(local_buffer))
       {
       memcpy(local_buffer, name, last);
-      local_buffer[last] = 0;
+      local_buffer[last] = '\0';
       name = local_buffer;
       }
     else
@@ -2849,7 +3041,8 @@
 
   // Now check the file node type.
 #if defined( _WIN32 )
-  DWORD attr = GetFileAttributesW(Encoding::ToWide(name).c_str());
+  DWORD attr = GetFileAttributesW(
+    SystemTools::ConvertToWindowsExtendedPath(name).c_str());
   if (attr != INVALID_FILE_ATTRIBUTES)
     {
     return (attr & FILE_ATTRIBUTE_DIRECTORY) != 0;
@@ -2866,14 +3059,14 @@
     }
 }
 
-bool SystemTools::FileIsSymlink(const char* name)
+bool SystemTools::FileIsSymlink(const kwsys_stl::string& name)
 {
 #if defined( _WIN32 )
   (void)name;
   return false;
 #else
   struct stat fs;
-  if(lstat(name, &fs) == 0)
+  if(lstat(name.c_str(), &fs) == 0)
     {
     return S_ISLNK(fs.st_mode);
     }
@@ -2922,7 +3115,7 @@
 }
 #endif
 
-int SystemTools::ChangeDirectory(const char *dir)
+int SystemTools::ChangeDirectory(const kwsys_stl::string& dir)
 {
   return Chdir(dir);
 }
@@ -2959,7 +3152,7 @@
   file = "";
   SystemTools::ConvertToUnixSlashes(dir);
 
-  if(!SystemTools::FileIsDirectory(dir.c_str()))
+  if(!SystemTools::FileIsDirectory(dir))
     {
     kwsys_stl::string::size_type slashPos = dir.rfind("/");
     if(slashPos != kwsys_stl::string::npos)
@@ -2973,7 +3166,7 @@
       dir = "";
       }
     }
-  if(!(dir == "") && !SystemTools::FileIsDirectory(dir.c_str()))
+  if(!(dir.empty()) && !SystemTools::FileIsDirectory(dir))
     {
     kwsys_stl::string oldDir = in_name;
     SystemTools::ConvertToUnixSlashes(oldDir);
@@ -2994,8 +3187,8 @@
   kwsys_stl::string self = argv0 ? argv0 : "";
   failures.push_back(self);
   SystemTools::ConvertToUnixSlashes(self);
-  self = SystemTools::FindProgram(self.c_str());
-  if(!SystemTools::FileExists(self.c_str()))
+  self = SystemTools::FindProgram(self);
+  if(!SystemTools::FileExists(self))
     {
     if(buildDir)
       {
@@ -3013,7 +3206,7 @@
     }
   if(installPrefix)
     {
-    if(!SystemTools::FileExists(self.c_str()))
+    if(!SystemTools::FileExists(self))
       {
       failures.push_back(self);
       self = installPrefix;
@@ -3021,7 +3214,7 @@
       self +=  exeName;
       }
     }
-  if(!SystemTools::FileExists(self.c_str()))
+  if(!SystemTools::FileExists(self))
     {
     failures.push_back(self);
     kwsys_ios::ostringstream msg;
@@ -3062,12 +3255,12 @@
   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() ) )
+  if( SystemTools::FileIsDirectory( path_a ) )
     {
     // Make sure the path is a full path and does not contain no '..'
     // Ken--the following code is incorrect. .. can be in a valid path
     // for example  /home/martink/MyHubba...Hubba/Src
-    if( SystemTools::FileIsFullPath(path_b.c_str()) && path_b.find("..")
+    if( SystemTools::FileIsFullPath(path_b) && path_b.find("..")
         == kwsys_stl::string::npos )
       {
       // Before inserting make sure path ends with '/'
@@ -3224,7 +3417,7 @@
 }
 
 // compute the relative path from here to there
-kwsys_stl::string SystemTools::RelativePath(const char* local, const char* remote)
+kwsys_stl::string SystemTools::RelativePath(const kwsys_stl::string& local, const kwsys_stl::string& remote)
 {
   if(!SystemTools::FileIsFullPath(local))
     {
@@ -3235,9 +3428,12 @@
     return "";
     }
 
+  kwsys_stl::string l = SystemTools::CollapseFullPath(local);
+  kwsys_stl::string r = SystemTools::CollapseFullPath(remote);
+
   // split up both paths into arrays of strings using / as a separator
-  kwsys_stl::vector<kwsys::String> localSplit = SystemTools::SplitString(local, '/', true);
-  kwsys_stl::vector<kwsys::String> remoteSplit = SystemTools::SplitString(remote, '/', true);
+  kwsys_stl::vector<kwsys::String> localSplit = SystemTools::SplitString(l, '/', true);
+  kwsys_stl::vector<kwsys::String> remoteSplit = SystemTools::SplitString(r, '/', true);
   kwsys_stl::vector<kwsys::String> commonPath; // store shared parts of path in this array
   kwsys_stl::vector<kwsys::String> finalPath;  // store the final relative path here
   // count up how many matching directory names there are from the start
@@ -3343,6 +3539,16 @@
     kwsys_stl::string test_str = casePath;
     test_str += path_components[idx];
 
+    // If path component contains wildcards, we skip matching
+    // because these filenames are not allowed on windows,
+    // and we do not want to match a different file.
+    if(path_components[idx].find('*') != kwsys_stl::string::npos ||
+       path_components[idx].find('?') != kwsys_stl::string::npos)
+      {
+      casePath = "";
+      return 0;
+      }
+
     WIN32_FIND_DATAW findData;
     HANDLE hFind = ::FindFirstFileW(Encoding::ToWide(test_str).c_str(),
       &findData);
@@ -3614,7 +3820,7 @@
 }
 
 //----------------------------------------------------------------------------
-bool SystemTools::Split(const char* str, kwsys_stl::vector<kwsys_stl::string>& lines, char separator)
+bool SystemTools::Split(const kwsys_stl::string& str, kwsys_stl::vector<kwsys_stl::string>& lines, char separator)
 {
   kwsys_stl::string data(str);
   kwsys_stl::string::size_type lpos = 0;
@@ -3638,7 +3844,7 @@
 }
 
 //----------------------------------------------------------------------------
-bool SystemTools::Split(const char* str, kwsys_stl::vector<kwsys_stl::string>& lines)
+bool SystemTools::Split(const kwsys_stl::string& str, kwsys_stl::vector<kwsys_stl::string>& lines)
 {
   kwsys_stl::string data(str);
   kwsys_stl::string::size_type lpos = 0;
@@ -3931,7 +4137,7 @@
       }
     temp += filename_base;
 
-    if (SystemTools::FileExists(temp.c_str()))
+    if (SystemTools::FileExists(temp))
       {
       res = true;
       filename_found = temp;
@@ -3980,9 +4186,18 @@
   return res;
 }
 
+bool SystemTools::FileIsFullPath(const kwsys_stl::string& in_name)
+{
+  return SystemTools::FileIsFullPath(in_name.c_str(), in_name.size());
+}
+
 bool SystemTools::FileIsFullPath(const char* in_name)
 {
-  size_t len = strlen(in_name);
+  return SystemTools::FileIsFullPath(in_name, in_name[0] ? (in_name[1] ? 2 : 1) : 0);
+}
+
+bool SystemTools::FileIsFullPath(const char* in_name, size_t len)
+{
 #if defined(_WIN32) || defined(__CYGWIN__)
   // On Windows, the name must be at least two characters long.
   if(len < 2)
@@ -4041,7 +4256,7 @@
   kwsys_stl::wstring wtempPath = Encoding::ToWide(tempPath);
   kwsys_stl::vector<wchar_t> buffer(wtempPath.size()+1);
   buffer[0] = 0;
-  ret = GetShortPathNameW(Encoding::ToWide(tempPath).c_str(),
+  ret = GetShortPathNameW(wtempPath.c_str(),
     &buffer[0], static_cast<DWORD>(wtempPath.size()));
 
   if(buffer[0] == 0 || ret > wtempPath.size())
@@ -4091,7 +4306,7 @@
     {
     kwsys_stl::string tryProg = dir.substr(0, spacePos);
     // See if the file exists
-    if(SystemTools::FileExists(tryProg.c_str()))
+    if(SystemTools::FileExists(tryProg))
       {
       program = tryProg;
       // remove trailing spaces from program
@@ -4105,7 +4320,7 @@
       return;
       }
     // Now try and find the program in the path
-    findProg = SystemTools::FindProgram(tryProg.c_str(), e);
+    findProg = SystemTools::FindProgram(tryProg, e);
     if(!findProg.empty())
       {
       program = findProg;
@@ -4277,9 +4492,14 @@
     {
     return false;
     }
+  return SystemTools::GetPermissions(kwsys_stl::string(file), mode);
+}
 
+bool SystemTools::GetPermissions(const kwsys_stl::string& file, mode_t& mode)
+{
 #if defined(_WIN32)
-  DWORD attr = GetFileAttributesW(Encoding::ToWide(file).c_str());
+  DWORD attr = GetFileAttributesW(
+    SystemTools::ConvertToWindowsExtendedPath(file).c_str());
   if(attr == INVALID_FILE_ATTRIBUTES)
     {
     return false;
@@ -4301,7 +4521,8 @@
     {
     mode |= S_IFREG;
     }
-  const char* ext = strrchr(file, '.');
+  size_t dotPos = file.rfind('.');
+  const char* ext = dotPos == file.npos ? 0 : (file.c_str() + dotPos);
   if(ext && (Strucmp(ext, ".exe") == 0 ||
     Strucmp(ext, ".com") == 0 ||
     Strucmp(ext, ".cmd") == 0 ||
@@ -4311,7 +4532,7 @@
     }
 #else
   struct stat st;
-  if ( stat(file, &st) < 0 )
+  if ( stat(file.c_str(), &st) < 0 )
     {
     return false;
     }
@@ -4326,14 +4547,20 @@
     {
     return false;
     }
+  return SystemTools::SetPermissions(kwsys_stl::string(file), mode);
+}
+
+bool SystemTools::SetPermissions(const kwsys_stl::string& file, mode_t mode)
+{
   if ( !SystemTools::FileExists(file) )
     {
     return false;
     }
 #ifdef _WIN32
-  if ( _wchmod(Encoding::ToWide(file).c_str(), mode) < 0 )
+  if ( _wchmod(SystemTools::ConvertToWindowsExtendedPath(file).c_str(),
+               mode) < 0 )
 #else
-  if ( chmod(file, mode) < 0 )
+  if ( chmod(file.c_str(), mode) < 0 )
 #endif
     {
     return false;
@@ -4342,7 +4569,7 @@
   return true;
 }
 
-kwsys_stl::string SystemTools::GetParentDirectory(const char* fileOrDir)
+kwsys_stl::string SystemTools::GetParentDirectory(const kwsys_stl::string& fileOrDir)
 {
   return SystemTools::GetFilenamePath(fileOrDir);
 }
@@ -4389,111 +4616,6 @@
 #endif
 }
 
-void SystemTools::ConvertWindowsCommandLineToUnixArguments(
-  const char *cmd_line, int *argc, char ***argv)
-{
-  if (!cmd_line || !argc || !argv)
-    {
-    return;
-    }
-
-  // A space delimites an argument except when it is inside a quote
-
-  (*argc) = 1;
-
-  size_t cmd_line_len = strlen(cmd_line);
-
-  size_t i;
-  for (i = 0; i < cmd_line_len; i++)
-    {
-    while (isspace(cmd_line[i]) && i < cmd_line_len)
-      {
-      i++;
-      }
-    if (i < cmd_line_len)
-      {
-      if (cmd_line[i] == '\"')
-        {
-        i++;
-        while (cmd_line[i] != '\"' && i < cmd_line_len)
-          {
-          i++;
-          }
-        (*argc)++;
-        }
-      else
-        {
-        while (!isspace(cmd_line[i]) && i < cmd_line_len)
-          {
-          i++;
-          }
-        (*argc)++;
-        }
-      }
-    }
-
-  (*argv) = new char* [(*argc) + 1];
-  (*argv)[(*argc)] = NULL;
-
-  // Set the first arg to be the exec name
-
-  (*argv)[0] = new char [1024];
-#ifdef _WIN32
-  wchar_t tmp[1024];
-  ::GetModuleFileNameW(0, tmp, 1024);
-  strcpy((*argv)[0], Encoding::ToNarrow(tmp).c_str());
-#else
-  (*argv)[0][0] = '\0';
-#endif
-
-  // Allocate the others
-
-  int j;
-  for (j = 1; j < (*argc); j++)
-    {
-    (*argv)[j] = new char [cmd_line_len + 10];
-    }
-
-  // Grab the args
-
-  size_t pos;
-  int argc_idx = 1;
-
-  for (i = 0; i < cmd_line_len; i++)
-    {
-    while (isspace(cmd_line[i]) && i < cmd_line_len)
-      {
-      i++;
-      }
-    if (i < cmd_line_len)
-      {
-      if (cmd_line[i] == '\"')
-        {
-        i++;
-        pos = i;
-        while (cmd_line[i] != '\"' && i < cmd_line_len)
-          {
-          i++;
-          }
-        memcpy((*argv)[argc_idx], &cmd_line[pos], i - pos);
-        (*argv)[argc_idx][i - pos] = '\0';
-        argc_idx++;
-        }
-      else
-        {
-        pos = i;
-        while (!isspace(cmd_line[i]) && i < cmd_line_len)
-          {
-          i++;
-          }
-        memcpy((*argv)[argc_idx], &cmd_line[pos], i - pos);
-        (*argv)[argc_idx][i - pos] = '\0';
-        argc_idx++;
-        }
-      }
-    }
- }
-
 kwsys_stl::string SystemTools::GetOperatingSystemNameAndVersion()
 {
   kwsys_stl::string res;
@@ -4510,6 +4632,10 @@
   ZeroMemory(&osvi, sizeof(OSVERSIONINFOEXA));
   osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXA);
 
+#ifdef KWSYS_WINDOWS_DEPRECATED_GetVersionEx
+# pragma warning (push)
+# pragma warning (disable:4996)
+#endif
   bOsVersionInfoEx = GetVersionEx((OSVERSIONINFO *)&osvi);
   if (!bOsVersionInfoEx)
     {
@@ -4519,6 +4645,9 @@
       return 0;
       }
     }
+#ifdef KWSYS_WINDOWS_DEPRECATED_GetVersionEx
+# pragma warning (pop)
+#endif
 
   switch (osvi.dwPlatformId)
     {
diff --git a/Source/kwsys/SystemTools.hxx.in b/Source/kwsys/SystemTools.hxx.in
index fb55848..e88bc8f 100644
--- a/Source/kwsys/SystemTools.hxx.in
+++ b/Source/kwsys/SystemTools.hxx.in
@@ -158,7 +158,9 @@
    * Returns true if str1 starts (respectively ends) with str2
    */
   static bool StringStartsWith(const char* str1, const char* str2);
+  static bool StringStartsWith(const kwsys_stl::string& str1, const char* str2);
   static bool StringEndsWith(const char* str1, const char* str2);
+  static bool StringEndsWith(const kwsys_stl::string& str1, const char* str2);
 
   /**
    * Returns a pointer to the last occurence of str2 in str1
@@ -183,7 +185,7 @@
       s starts with a / then the first element of the returned array will
       be /, so /foo/bar will be [/, foo, bar]
   */  
-  static kwsys_stl::vector<String> SplitString(const char* s, char separator = '/', 
+  static kwsys_stl::vector<String> SplitString(const kwsys_stl::string& s, char separator = '/',
                                                bool isPath = false);
   /**
    * Perform a case-independent string comparison
@@ -201,8 +203,8 @@
    * Split a string on its newlines into multiple lines
    * Return false only if the last line stored had no newline
    */
-  static bool Split(const char* s, kwsys_stl::vector<kwsys_stl::string>& l);
-  static bool Split(const char* s, kwsys_stl::vector<kwsys_stl::string>& l, char separator);
+  static bool Split(const kwsys_stl::string& s, kwsys_stl::vector<kwsys_stl::string>& l);
+  static bool Split(const kwsys_stl::string& s, kwsys_stl::vector<kwsys_stl::string>& l, char separator);
   
   /** 
    * Return string with space added between capitalized words
@@ -249,18 +251,29 @@
    * Replace Windows file system slashes with Unix-style slashes.
    */
   static void ConvertToUnixSlashes(kwsys_stl::string& path);
-  
+
+#ifdef _WIN32
+  /**
+   * Convert the path to an extended length path to avoid MAX_PATH length
+   * limitations on Windows. If the input is a local path the result will be
+   * prefixed with \\?\; if the input is instead a network path, the result
+   * will be prefixed with \\?\UNC\. All output will also be converted to
+   * absolute paths with Windows-style backslashes.
+   **/
+  static kwsys_stl::wstring ConvertToWindowsExtendedPath(const kwsys_stl::string&);
+#endif
+
   /**
    * For windows this calls ConvertToWindowsOutputPath and for unix
    * it calls ConvertToUnixOutputPath
    */
-  static kwsys_stl::string ConvertToOutputPath(const char*);
+  static kwsys_stl::string ConvertToOutputPath(const kwsys_stl::string&);
 
   /**
    * Convert the path to a string that can be used in a unix makefile.
    * double slashes are removed, and spaces are escaped.
    */
-  static kwsys_stl::string ConvertToUnixOutputPath(const char*);
+  static kwsys_stl::string ConvertToUnixOutputPath(const kwsys_stl::string&);
 
   /**
    * Convert the path to string that can be used in a windows project or
@@ -268,7 +281,7 @@
    * the string, the slashes are converted to windows style backslashes, and
    * if there are spaces in the string it is double quoted.
    */
-  static kwsys_stl::string ConvertToWindowsOutputPath(const char*);
+  static kwsys_stl::string ConvertToWindowsOutputPath(const kwsys_stl::string&);
 
   /**
    * Return true if a file exists in the current directory.
@@ -277,7 +290,9 @@
    * if it is a file or a directory.
    */
   static bool FileExists(const char* filename, bool isFile);
+  static bool FileExists(const kwsys_stl::string& filename, bool isFile);
   static bool FileExists(const char* filename);
+  static bool FileExists(const kwsys_stl::string& filename);
 
   /**
    * Converts Cygwin path to Win32 path. Uses dictionary container for
@@ -296,7 +311,7 @@
   /**
      Change the modification time or create a file
   */
-  static bool Touch(const char* filename, bool create);
+  static bool Touch(const kwsys_stl::string& filename, bool create);
   
   /**
    *  Compare file modification times.
@@ -304,7 +319,8 @@
    *  When true is returned, result has -1, 0, +1 for
    *  f1 older, same, or newer than f2.
    */
-  static bool FileTimeCompare(const char* f1, const char* f2,
+  static bool FileTimeCompare(const kwsys_stl::string& f1,
+                              const kwsys_stl::string& f2,
                               int* result);
 
   /**
@@ -366,7 +382,7 @@
    * the event of an error (non-existent path, permissions issue,
    * etc.) the original path is returned.
    */
-  static kwsys_stl::string GetRealPath(const char* path);
+  static kwsys_stl::string GetRealPath(const kwsys_stl::string& path);
 
   /**
    * Split a path name into its root component and the rest of the
@@ -459,6 +475,7 @@
   /**
    * Return whether the path represents a full path (not relative)
    */
+  static bool FileIsFullPath(const kwsys_stl::string&);
   static bool FileIsFullPath(const char*);
   
   /**
@@ -482,7 +499,7 @@
   /**
    * Get the parent directory of the directory or file
    */
-  static kwsys_stl::string GetParentDirectory(const char* fileOrDir);
+  static kwsys_stl::string GetParentDirectory(const kwsys_stl::string& fileOrDir);
 
   /**
    * Check if the given file or directory is in subdirectory of dir
@@ -497,7 +514,7 @@
   /**
    * Open a file considering unicode.
    */
-  static FILE* Fopen(const char* file, const char* mode);
+  static FILE* Fopen(const kwsys_stl::string& file, const char* mode);
 
   /**
    * Make a new directory if it is not there.  This function
@@ -505,35 +522,36 @@
    * prior to calling this function.  
    */
   static bool MakeDirectory(const char* path);
+  static bool MakeDirectory(const kwsys_stl::string& path);
 
   /**
    * Copy the source file to the destination file only
    * if the two files differ.
    */
-  static bool CopyFileIfDifferent(const char* source,
-                                  const char* destination);
+  static bool CopyFileIfDifferent(const kwsys_stl::string& source,
+                                  const kwsys_stl::string& destination);
 
   /**
    * Compare the contents of two files.  Return true if different
    */
-  static bool FilesDiffer(const char* source, const char* destination);
+  static bool FilesDiffer(const kwsys_stl::string& source, const kwsys_stl::string& destination);
 
   /**
    * Return true if the two files are the same file
    */
-  static bool SameFile(const char* file1, const char* file2);
+  static bool SameFile(const kwsys_stl::string& file1, const kwsys_stl::string& file2);
 
   /**
    * Copy a file.
    */
-  static bool CopyFileAlways(const char* source, const char* destination);
+  static bool CopyFileAlways(const kwsys_stl::string& source, const kwsys_stl::string& destination);
 
   /**
    * Copy a file.  If the "always" argument is true the file is always
    * copied.  If it is false, the file is copied only if it is new or
    * has changed.
    */
-  static bool CopyAFile(const char* source, const char* destination,
+  static bool CopyAFile(const kwsys_stl::string& source, const kwsys_stl::string& destination,
                         bool always = true);
 
   /**
@@ -542,18 +560,18 @@
    * always copied.  If it is false, only files that have changed or
    * are new are copied.
    */
-  static bool CopyADirectory(const char* source, const char* destination,
+  static bool CopyADirectory(const kwsys_stl::string& source, const kwsys_stl::string& destination,
                              bool always = true);
   
   /**
    * Remove a file
    */
-  static bool RemoveFile(const char* source);
+  static bool RemoveFile(const kwsys_stl::string& source);
   
   /**
    * Remove a directory
    */
-  static bool RemoveADirectory(const char* source);
+  static bool RemoveADirectory(const kwsys_stl::string& source);
 
   /**
    * Get the maximum full file path length
@@ -583,12 +601,17 @@
    */
   static kwsys_stl::string FindProgram(
     const char* name,
-    const kwsys_stl::vector<kwsys_stl::string>& path = 
+    const kwsys_stl::vector<kwsys_stl::string>& path =
+    kwsys_stl::vector<kwsys_stl::string>(),
+    bool no_system_path = false);
+  static kwsys_stl::string FindProgram(
+    const kwsys_stl::string& name,
+    const kwsys_stl::vector<kwsys_stl::string>& path =
     kwsys_stl::vector<kwsys_stl::string>(),
     bool no_system_path = false);
   static kwsys_stl::string FindProgram(
     const kwsys_stl::vector<kwsys_stl::string>& names,
-    const kwsys_stl::vector<kwsys_stl::string>& path = 
+    const kwsys_stl::vector<kwsys_stl::string>& path =
     kwsys_stl::vector<kwsys_stl::string>(),
     bool no_system_path = false);
 
@@ -596,18 +619,18 @@
    * Find a library in the system PATH, with optional extra paths
    */
   static kwsys_stl::string FindLibrary(
-    const char* name,
+    const kwsys_stl::string& name,
     const kwsys_stl::vector<kwsys_stl::string>& path);
   
   /**
    * Return true if the file is a directory
    */
-  static bool FileIsDirectory(const char* name);
+  static bool FileIsDirectory(const kwsys_stl::string& name);
   
   /**
    * Return true if the file is a symlink
    */
-  static bool FileIsSymlink(const char* name);
+  static bool FileIsSymlink(const kwsys_stl::string& name);
   
   /**
    * Return true if the file has a given signature (first set of bytes)
@@ -675,17 +698,17 @@
       /a/b/c/d to /a/b/c1/d1 -> ../../c1/d1
       from /usr/src to /usr/src/test/blah/foo.cpp -> test/blah/foo.cpp
   */
-  static kwsys_stl::string RelativePath(const char* local, const char* remote);
+  static kwsys_stl::string RelativePath(const kwsys_stl::string& local, const kwsys_stl::string& remote);
 
   /**
    * Return file's modified time
    */
-  static long int ModifiedTime(const char* filename);
+  static long int ModifiedTime(const kwsys_stl::string& filename);
 
   /**
    * Return file's creation time (Win32: works only for NTFS, not FAT)
    */
-  static long int CreationTime(const char* filename);
+  static long int CreationTime(const kwsys_stl::string& filename);
 
   #if defined( _MSC_VER )
   typedef unsigned short mode_t;
@@ -695,7 +718,9 @@
    * Get and set permissions of the file.
    */
   static bool GetPermissions(const char* file, mode_t& mode);
+  static bool GetPermissions(const kwsys_stl::string& file, mode_t& mode);
   static bool SetPermissions(const char* file, mode_t mode);
+  static bool SetPermissions(const kwsys_stl::string& file, mode_t mode);
 
   /** -----------------------------------------------------------------
    *               Time Manipulation Routines
@@ -782,7 +807,7 @@
   /**
    * Change directory to the directory specified
    */
-  static int ChangeDirectory(const char* dir);
+  static int ChangeDirectory(const kwsys_stl::string& dir);
 
   /**
    * Get the result of strerror(errno)
@@ -831,15 +856,6 @@
    */
   static kwsys_stl::string GetOperatingSystemNameAndVersion();
 
-  /**
-   * Convert windows-style arguments given as a command-line string
-   * into more traditional argc/argv arguments.
-   * Note that argv[0] will be assigned the executable name using
-   * the GetModuleFileName() function.
-   */
-  static void ConvertWindowsCommandLineToUnixArguments(
-    const char *cmd_line, int *argc, char ***argv);
-
   /** -----------------------------------------------------------------
    *               URL Manipulation Routines
    *  -----------------------------------------------------------------
@@ -890,6 +906,11 @@
     }
 
   /**
+   * Actual implementation of FileIsFullPath.
+   */
+  static bool FileIsFullPath(const char*, size_t);
+
+  /**
    * Find a filename (file or directory) in the system PATH, with
    * optional extra paths.
    */
diff --git a/Source/kwsys/Terminal.c b/Source/kwsys/Terminal.c
index 6d7ec41..e13003f 100644
--- a/Source/kwsys/Terminal.c
+++ b/Source/kwsys/Terminal.c
@@ -104,11 +104,11 @@
 }
 
 /*--------------------------------------------------------------------------*/
-/* Detect cases when a stream is definately not interactive.  */
+/* Detect cases when a stream is definitely not interactive.  */
 #if !defined(KWSYS_TERMINAL_ISATTY_WORKS)
 static int kwsysTerminalStreamIsNotInteractive(FILE* stream)
 {
-  /* The given stream is definately not interactive if it is a regular
+  /* The given stream is definitely not interactive if it is a regular
      file.  */
   struct stat stream_stat;
   if(fstat(fileno(stream), &stream_stat) == 0)
@@ -212,7 +212,7 @@
   (void)default_tty;
   return isatty(fileno(stream))? 1:0;
 #else
-  /* Check for cases in which the stream is definately not a tty.  */
+  /* Check for cases in which the stream is definitely not a tty.  */
   if(kwsysTerminalStreamIsNotInteractive(stream))
     {
     return 0;
diff --git a/Source/kwsys/kwsysPlatformTests.cmake b/Source/kwsys/kwsysPlatformTests.cmake
index f9ee254..16bc969 100644
--- a/Source/kwsys/kwsysPlatformTests.cmake
+++ b/Source/kwsys/kwsysPlatformTests.cmake
@@ -13,7 +13,7 @@
 SET(KWSYS_PLATFORM_TEST_FILE_CXX kwsysPlatformTestsCXX.cxx)
 
 MACRO(KWSYS_PLATFORM_TEST lang var description invert)
-  IF("${var}_COMPILED" MATCHES "^${var}_COMPILED$")
+  IF(NOT DEFINED ${var}_COMPILED)
     MESSAGE(STATUS "${description}")
     TRY_COMPILE(${var}_COMPILED
       ${CMAKE_CURRENT_BINARY_DIR}
@@ -43,7 +43,7 @@
         MESSAGE(STATUS "${description} - no")
       ENDIF(${var}_COMPILED)
     ENDIF(${invert} MATCHES INVERT)
-  ENDIF("${var}_COMPILED" MATCHES "^${var}_COMPILED$")
+  ENDIF()
   IF(${invert} MATCHES INVERT)
     IF(${var}_COMPILED)
       SET(${var} 0)
@@ -60,7 +60,7 @@
 ENDMACRO(KWSYS_PLATFORM_TEST)
 
 MACRO(KWSYS_PLATFORM_TEST_RUN lang var description invert)
-  IF("${var}" MATCHES "^${var}$")
+  IF(NOT DEFINED ${var})
     MESSAGE(STATUS "${description}")
     TRY_RUN(${var} ${var}_COMPILED
       ${CMAKE_CURRENT_BINARY_DIR}
@@ -107,7 +107,7 @@
         MESSAGE(STATUS "${description} - failed to compile")
       ENDIF(${var}_COMPILED)
     ENDIF(${invert} MATCHES INVERT)
-  ENDIF("${var}" MATCHES "^${var}$")
+  ENDIF()
 
   IF(${invert} MATCHES INVERT)
     IF(${var}_COMPILED)
diff --git a/Source/kwsys/testCommandLineArguments1.cxx b/Source/kwsys/testCommandLineArguments1.cxx
index 3b84c38..b65c37f 100644
--- a/Source/kwsys/testCommandLineArguments1.cxx
+++ b/Source/kwsys/testCommandLineArguments1.cxx
@@ -21,6 +21,7 @@
 # include "kwsys_ios_iostream.h.in"
 #endif
 
+#include <assert.h> /* assert */
 #include <string.h> /* strcmp */
 
 int testCommandLineArguments1(int argc, char* argv[])
@@ -83,6 +84,7 @@
     }
   for ( cc = 0; cc < newArgc; ++ cc )
     {
+    assert(newArgv[cc]); /* Quiet Clang scan-build. */
     kwsys_ios::cout << "Unused argument[" << cc << "] = [" << newArgv[cc] << "]"
       << kwsys_ios::endl;
     if ( cc >= 9 )
diff --git a/Source/kwsys/testDynamicLoader.cxx b/Source/kwsys/testDynamicLoader.cxx
index 1bff707..58adb84 100644
--- a/Source/kwsys/testDynamicLoader.cxx
+++ b/Source/kwsys/testDynamicLoader.cxx
@@ -108,7 +108,7 @@
   // Make sure that inexistent lib is giving correct result
   res += TestDynamicLoader("azerty_", "foo_bar",0,0,0);
   // Make sure that random binary file cannot be assimilated as dylib
-  res += TestDynamicLoader(TEST_SYSTEMTOOLS_BIN_FILE, "wp",0,0,0);
+  res += TestDynamicLoader(TEST_SYSTEMTOOLS_SOURCE_DIR "/testSystemTools.bin", "wp",0,0,0);
 #endif
 
 #ifdef __linux__
diff --git a/Source/kwsys/testProcess.c b/Source/kwsys/testProcess.c
index 6d5eb71..47c3fb0 100644
--- a/Source/kwsys/testProcess.c
+++ b/Source/kwsys/testProcess.c
@@ -11,13 +11,16 @@
 ============================================================================*/
 #include "kwsysPrivate.h"
 #include KWSYS_HEADER(Process.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 "Encoding.h.in"
 #endif
 
+#include <assert.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
@@ -102,6 +105,7 @@
   fprintf(stderr, "Output before crash on stderr from crash test.\n");  
   fflush(stdout);
   fflush(stderr);
+  assert(invalidAddress); /* Quiet Clang scan-build. */
   /* Provoke deliberate crash by writing to the invalid address. */
   *invalidAddress = 0;
   fprintf(stdout, "Output after crash on stdout from crash test.\n");
@@ -393,6 +397,19 @@
 int main(int argc, const char* argv[])
 {
   int n = 0;
+
+#ifdef _WIN32
+  int i;
+  char new_args[10][_MAX_PATH];
+  LPWSTR* w_av = CommandLineToArgvW(GetCommandLineW(), &argc);
+  for(i=0; i<argc; i++)
+  {
+    kwsysEncoding_wcstombs(new_args[i], w_av[i], _MAX_PATH);
+    argv[i] = new_args[i];
+  }
+  LocalFree(w_av);
+#endif
+
 #if 0
     {
     HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
diff --git a/Source/kwsys/testSystemTools.cxx b/Source/kwsys/testSystemTools.cxx
index 69825a8..b41532b 100644
--- a/Source/kwsys/testSystemTools.cxx
+++ b/Source/kwsys/testSystemTools.cxx
@@ -98,33 +98,125 @@
 static bool CheckFileOperations()
 {
   bool res = true;
+  const kwsys_stl::string testBinFile(TEST_SYSTEMTOOLS_SOURCE_DIR
+    "/testSystemTools.bin");
+  const kwsys_stl::string testTxtFile(TEST_SYSTEMTOOLS_SOURCE_DIR
+    "/testSystemTools.cxx");
+  const kwsys_stl::string testNewDir(TEST_SYSTEMTOOLS_BINARY_DIR
+    "/testSystemToolsNewDir");
+  const kwsys_stl::string testNewFile(testNewDir + "/testNewFile.txt");
 
-  if (kwsys::SystemTools::DetectFileType(TEST_SYSTEMTOOLS_BIN_FILE) !=
+  if (kwsys::SystemTools::DetectFileType(testBinFile.c_str()) !=
       kwsys::SystemTools::FileTypeBinary)
     {
     kwsys_ios::cerr
       << "Problem with DetectFileType - failed to detect type of: "
-      << TEST_SYSTEMTOOLS_BIN_FILE << kwsys_ios::endl;
+      << testBinFile << kwsys_ios::endl;
     res = false;
     }
 
-  if (kwsys::SystemTools::DetectFileType(TEST_SYSTEMTOOLS_SRC_FILE) !=
+  if (kwsys::SystemTools::DetectFileType(testTxtFile.c_str()) !=
       kwsys::SystemTools::FileTypeText)
     {
     kwsys_ios::cerr
       << "Problem with DetectFileType - failed to detect type of: "
-      << TEST_SYSTEMTOOLS_SRC_FILE << kwsys_ios::endl;
+      << testTxtFile << kwsys_ios::endl;
     res = false;
     }
-  
-  if (kwsys::SystemTools::FileLength(TEST_SYSTEMTOOLS_BIN_FILE) != 766)
+
+  if (kwsys::SystemTools::FileLength(testBinFile.c_str()) != 766)
     {
     kwsys_ios::cerr
       << "Problem with FileLength - incorrect length for: "
-      << TEST_SYSTEMTOOLS_BIN_FILE << kwsys_ios::endl;
-    res = false;    
+      << testBinFile << kwsys_ios::endl;
+    res = false;
     }
 
+  if (!kwsys::SystemTools::MakeDirectory(testNewDir))
+    {
+    kwsys_ios::cerr
+      << "Problem with MakeDirectory for: "
+      << testNewDir << kwsys_ios::endl;
+    res = false;
+    }
+
+  if (!kwsys::SystemTools::Touch(testNewFile.c_str(), true))
+    {
+    kwsys_ios::cerr
+      << "Problem with Touch for: "
+      << testNewFile << kwsys_ios::endl;
+    res = false;
+    }
+
+  if (!kwsys::SystemTools::RemoveFile(testNewFile))
+    {
+    kwsys_ios::cerr
+      << "Problem with RemoveFile: "
+      << testNewFile << kwsys_ios::endl;
+    res = false;
+    }
+
+  kwsys::SystemTools::Touch(testNewFile.c_str(), true);
+  if (!kwsys::SystemTools::RemoveADirectory(testNewDir))
+    {
+    kwsys_ios::cerr
+      << "Problem with RemoveADirectory for: "
+      << testNewDir << kwsys_ios::endl;
+    res = false;
+    }
+
+#ifdef KWSYS_TEST_SYSTEMTOOLS_LONG_PATHS
+  // Perform the same file and directory creation and deletion tests but
+  // with paths > 256 characters in length.
+
+  const kwsys_stl::string testNewLongDir(
+    TEST_SYSTEMTOOLS_BINARY_DIR "/"
+    "012345678901234567890123456789012345678901234567890123456789"
+    "012345678901234567890123456789012345678901234567890123456789"
+    "012345678901234567890123456789012345678901234567890123456789"
+    "012345678901234567890123456789012345678901234567890123456789"
+    "01234567890123");
+  const kwsys_stl::string testNewLongFile(testNewLongDir + "/"
+    "012345678901234567890123456789012345678901234567890123456789"
+    "012345678901234567890123456789012345678901234567890123456789"
+    "012345678901234567890123456789012345678901234567890123456789"
+    "012345678901234567890123456789012345678901234567890123456789"
+    "0123456789.txt");
+
+  if (!kwsys::SystemTools::MakeDirectory(testNewLongDir))
+    {
+    kwsys_ios::cerr
+      << "Problem with MakeDirectory for: "
+      << testNewLongDir << kwsys_ios::endl;
+    res = false;
+    }
+
+  if (!kwsys::SystemTools::Touch(testNewLongFile.c_str(), true))
+    {
+    kwsys_ios::cerr
+      << "Problem with Touch for: "
+      << testNewLongFile << kwsys_ios::endl;
+    res = false;
+    }
+
+  if (!kwsys::SystemTools::RemoveFile(testNewLongFile))
+    {
+    kwsys_ios::cerr
+      << "Problem with RemoveFile: "
+      << testNewLongFile << kwsys_ios::endl;
+    res = false;
+    }
+
+  kwsys::SystemTools::Touch(testNewLongFile.c_str(), true);
+  if (!kwsys::SystemTools::RemoveADirectory(testNewLongDir))
+    {
+    kwsys_ios::cerr
+      << "Problem with RemoveADirectory for: "
+      << testNewLongDir << kwsys_ios::endl;
+    res = false;
+    }
+#endif
+
   return res;
 }
 
@@ -138,7 +230,7 @@
     {
     kwsys_ios::cerr
       << "Problem with CapitalizedWords "
-      << TEST_SYSTEMTOOLS_SRC_FILE << kwsys_ios::endl;
+      << '"' << test << '"' << kwsys_ios::endl;
     res = false;    
     }
 
@@ -148,7 +240,7 @@
     {
     kwsys_ios::cerr
       << "Problem with UnCapitalizedWords "
-      << TEST_SYSTEMTOOLS_SRC_FILE << kwsys_ios::endl;
+      << '"' << test << '"' << kwsys_ios::endl;
     res = false;    
     }
 
@@ -158,7 +250,7 @@
     {
     kwsys_ios::cerr
       << "Problem with AddSpaceBetweenCapitalizedWords "
-      << TEST_SYSTEMTOOLS_SRC_FILE << kwsys_ios::endl;
+      << '"' << test << '"' << kwsys_ios::endl;
     res = false;    
     }
 
@@ -168,7 +260,7 @@
     {
     kwsys_ios::cerr
       << "Problem with AppendStrings "
-      << TEST_SYSTEMTOOLS_SRC_FILE << kwsys_ios::endl;
+      << "\"Mary Had A\" \" Little Lamb.\"" << kwsys_ios::endl;
     res = false;    
     }
   delete [] cres;
@@ -179,7 +271,7 @@
     {
     kwsys_ios::cerr
       << "Problem with AppendStrings "
-      << TEST_SYSTEMTOOLS_SRC_FILE << kwsys_ios::endl;
+      << "\"Mary Had\" \" A \" \"Little Lamb.\"" << kwsys_ios::endl;
     res = false;    
     }
   delete [] cres;
@@ -188,7 +280,7 @@
     {
     kwsys_ios::cerr
       << "Problem with CountChar "
-      << TEST_SYSTEMTOOLS_SRC_FILE << kwsys_ios::endl;
+      << "\"Mary Had A Little Lamb.\"" << kwsys_ios::endl;
     res = false;    
     }
 
@@ -198,7 +290,7 @@
     {
     kwsys_ios::cerr
       << "Problem with RemoveChars "
-      << TEST_SYSTEMTOOLS_SRC_FILE << kwsys_ios::endl;
+      << "\"Mary Had A Little Lamb.\"" << kwsys_ios::endl;
     res = false;    
     }
   delete [] cres;
@@ -209,7 +301,7 @@
     {
     kwsys_ios::cerr
       << "Problem with RemoveCharsButUpperHex "
-      << TEST_SYSTEMTOOLS_SRC_FILE << kwsys_ios::endl;
+      << "\"Mary Had A Little Lamb.\"" << kwsys_ios::endl;
     res = false;    
     }
   delete [] cres;
@@ -221,7 +313,7 @@
     {
     kwsys_ios::cerr
       << "Problem with ReplaceChars "
-      << TEST_SYSTEMTOOLS_SRC_FILE << kwsys_ios::endl;
+      << "\"Mary Had A Little Lamb.\"" << kwsys_ios::endl;
     res = false;    
     }
   delete [] cres2;
@@ -231,7 +323,7 @@
     {
     kwsys_ios::cerr
       << "Problem with StringStartsWith "
-      << TEST_SYSTEMTOOLS_SRC_FILE << kwsys_ios::endl;
+      << "\"Mary Had A Little Lamb.\"" << kwsys_ios::endl;
     res = false;    
     }
 
@@ -240,7 +332,7 @@
     {
     kwsys_ios::cerr
       << "Problem with StringEndsWith "
-      << TEST_SYSTEMTOOLS_SRC_FILE << kwsys_ios::endl;
+      << "\"Mary Had A Little Lamb.\"" << kwsys_ios::endl;
     res = false;    
     }
 
@@ -249,7 +341,7 @@
     {
     kwsys_ios::cerr
       << "Problem with DuplicateString "
-      << TEST_SYSTEMTOOLS_SRC_FILE << kwsys_ios::endl;
+      << "\"Mary Had A Little Lamb.\"" << kwsys_ios::endl;
     res = false;    
     }
   delete [] cres;
@@ -260,7 +352,7 @@
     {
     kwsys_ios::cerr
       << "Problem with CropString "
-      << TEST_SYSTEMTOOLS_SRC_FILE << kwsys_ios::endl;
+      << "\"Mary Had A Little Lamb.\"" << kwsys_ios::endl;
     res = false;    
     }
 
@@ -271,16 +363,124 @@
     {
     kwsys_ios::cerr
       << "Problem with Split "
-      << TEST_SYSTEMTOOLS_SRC_FILE << kwsys_ios::endl;
-    res = false;    
+      << "\"Mary Had A Little Lamb.\"" << kwsys_ios::endl;
+    res = false;
     }
 
+#ifdef _WIN32
+  if (kwsys::SystemTools::ConvertToWindowsExtendedPath
+      ("L:\\Local Mojo\\Hex Power Pack\\Iffy Voodoo") !=
+      L"\\\\?\\L:\\Local Mojo\\Hex Power Pack\\Iffy Voodoo")
+    {
+    kwsys_ios::cerr
+      << "Problem with ConvertToWindowsExtendedPath "
+      << "\"L:\\Local Mojo\\Hex Power Pack\\Iffy Voodoo\""
+      << kwsys_ios::endl;
+    res = false;
+    }
+
+  if (kwsys::SystemTools::ConvertToWindowsExtendedPath
+      ("L:/Local Mojo/Hex Power Pack/Iffy Voodoo") !=
+      L"\\\\?\\L:\\Local Mojo\\Hex Power Pack\\Iffy Voodoo")
+    {
+    kwsys_ios::cerr
+      << "Problem with ConvertToWindowsExtendedPath "
+      << "\"L:/Local Mojo/Hex Power Pack/Iffy Voodoo\""
+      << kwsys_ios::endl;
+    res = false;
+    }
+
+  if (kwsys::SystemTools::ConvertToWindowsExtendedPath
+      ("\\\\Foo\\Local Mojo\\Hex Power Pack\\Iffy Voodoo") !=
+      L"\\\\?\\UNC\\Foo\\Local Mojo\\Hex Power Pack\\Iffy Voodoo")
+    {
+    kwsys_ios::cerr
+      << "Problem with ConvertToWindowsExtendedPath "
+      << "\"\\\\Foo\\Local Mojo\\Hex Power Pack\\Iffy Voodoo\""
+      << kwsys_ios::endl;
+    res = false;
+    }
+
+  if (kwsys::SystemTools::ConvertToWindowsExtendedPath
+      ("//Foo/Local Mojo/Hex Power Pack/Iffy Voodoo") !=
+      L"\\\\?\\UNC\\Foo\\Local Mojo\\Hex Power Pack\\Iffy Voodoo")
+    {
+    kwsys_ios::cerr
+      << "Problem with ConvertToWindowsExtendedPath "
+      << "\"//Foo/Local Mojo/Hex Power Pack/Iffy Voodoo\""
+      << kwsys_ios::endl;
+    res = false;
+    }
+
+  if (kwsys::SystemTools::ConvertToWindowsExtendedPath("//") !=
+      L"//")
+    {
+    kwsys_ios::cerr
+      << "Problem with ConvertToWindowsExtendedPath "
+      << "\"//\""
+      << kwsys_ios::endl;
+    res = false;
+    }
+
+  if (kwsys::SystemTools::ConvertToWindowsExtendedPath("\\\\.\\") !=
+      L"\\\\.\\")
+    {
+    kwsys_ios::cerr
+      << "Problem with ConvertToWindowsExtendedPath "
+      << "\"\\\\.\\\""
+      << kwsys_ios::endl;
+    res = false;
+    }
+
+  if (kwsys::SystemTools::ConvertToWindowsExtendedPath("\\\\.\\X") !=
+      L"\\\\.\\X")
+    {
+    kwsys_ios::cerr
+      << "Problem with ConvertToWindowsExtendedPath "
+      << "\"\\\\.\\X\""
+      << kwsys_ios::endl;
+    res = false;
+    }
+
+  if (kwsys::SystemTools::ConvertToWindowsExtendedPath("\\\\.\\X:") !=
+      L"\\\\?\\X:")
+    {
+    kwsys_ios::cerr
+      << "Problem with ConvertToWindowsExtendedPath "
+      << "\"\\\\.\\X:\""
+      << kwsys_ios::endl;
+    res = false;
+    }
+
+  if (kwsys::SystemTools::ConvertToWindowsExtendedPath("\\\\.\\X:\\") !=
+      L"\\\\?\\X:\\")
+    {
+    kwsys_ios::cerr
+      << "Problem with ConvertToWindowsExtendedPath "
+      << "\"\\\\.\\X:\\\""
+      << kwsys_ios::endl;
+    res = false;
+    }
+
+  if (kwsys::SystemTools::ConvertToWindowsExtendedPath("NUL") !=
+      L"\\\\.\\NUL")
+    {
+    kwsys_ios::cerr
+      << "Problem with ConvertToWindowsExtendedPath "
+      << "\"NUL\""
+      << kwsys_ios::endl;
+    res = false;
+    }
+
+#endif
+
   if (kwsys::SystemTools::ConvertToWindowsOutputPath
       ("L://Local Mojo/Hex Power Pack/Iffy Voodoo") != 
       "\"L:\\Local Mojo\\Hex Power Pack\\Iffy Voodoo\"")
     {
     kwsys_ios::cerr
       << "Problem with ConvertToWindowsOutputPath "
+      << "\"L://Local Mojo/Hex Power Pack/Iffy Voodoo\""
       << kwsys_ios::endl;
     res = false;    
     }
@@ -291,6 +491,7 @@
     {
     kwsys_ios::cerr
       << "Problem with ConvertToWindowsOutputPath "
+      << "\"//grayson/Local Mojo/Hex Power Pack/Iffy Voodoo\""
       << kwsys_ios::endl;
     res = false;    
     }
@@ -301,29 +502,11 @@
     {
     kwsys_ios::cerr
       << "Problem with ConvertToUnixOutputPath "
+      << "\"//Local Mojo/Hex Power Pack/Iffy Voodoo\""
       << kwsys_ios::endl;
     res = false;    
     }
 
-  int targc;
-  char **targv;
-  kwsys::SystemTools::ConvertWindowsCommandLineToUnixArguments
-    ("\"Local Mojo\\Voodoo.asp\" -CastHex \"D:\\My Secret Mojo\\Voodoo.mp3\"", &targc, &targv);
-  if (targc != 4 || strcmp(targv[1],"Local Mojo\\Voodoo.asp") ||
-      strcmp(targv[2],"-CastHex") || 
-      strcmp(targv[3],"D:\\My Secret Mojo\\Voodoo.mp3"))
-    {
-    kwsys_ios::cerr
-      << "Problem with ConvertWindowsCommandLineToUnixArguments"
-      << TEST_SYSTEMTOOLS_SRC_FILE << kwsys_ios::endl;
-    res = false;    
-    }
-  for (;targc >=0; --targc)
-    {
-    delete [] targv[targc];
-    }
-  delete [] targv;
-
   return res;
 }
 
@@ -379,6 +562,55 @@
   return res;
 }
 
+
+static bool CheckRelativePath(
+  const kwsys_stl::string& local,
+  const kwsys_stl::string& remote,
+  const kwsys_stl::string& expected)
+{
+  kwsys_stl::string result = kwsys::SystemTools::RelativePath(local, remote);
+  if(expected != result)
+    {
+    kwsys_ios::cerr << "RelativePath(" << local << ", " << remote
+      << ")  yielded " << result << " instead of " << expected << kwsys_ios::endl;
+    return false;
+    }
+  return true;
+}
+
+static bool CheckRelativePaths()
+{
+  bool res = true;
+  res &= CheckRelativePath("/usr/share", "/bin/bash", "../../bin/bash");
+  res &= CheckRelativePath("/usr/./share/", "/bin/bash", "../../bin/bash");
+  res &= CheckRelativePath("/usr//share/", "/bin/bash", "../../bin/bash");
+  res &= CheckRelativePath("/usr/share/../bin/", "/bin/bash", "../../bin/bash");
+  res &= CheckRelativePath("/usr/share", "/usr/share//bin", "bin");
+  return res;
+}
+
+static bool CheckCollapsePath(
+  const kwsys_stl::string& path,
+  const kwsys_stl::string& expected)
+{
+  kwsys_stl::string result = kwsys::SystemTools::CollapseFullPath(path);
+  if(expected != result)
+    {
+    kwsys_ios::cerr << "CollapseFullPath(" << path
+      << ")  yielded " << result << " instead of " << expected << kwsys_ios::endl;
+    return false;
+    }
+  return true;
+}
+
+static bool CheckCollapsePath()
+{
+  bool res = true;
+  res &= CheckCollapsePath("/usr/share/*", "/usr/share/*");
+  res &= CheckCollapsePath("C:/Windows/*", "C:/Windows/*");
+  return res;
+}
+
 //----------------------------------------------------------------------------
 int testSystemTools(int, char*[])
 {
@@ -410,5 +642,9 @@
 
   res &= CheckEnvironmentOperations();
 
+  res &= CheckRelativePaths();
+
+  res &= CheckCollapsePath();
+
   return res ? 0 : 1;
 }
diff --git a/Source/kwsys/testSystemTools.h.in b/Source/kwsys/testSystemTools.h.in
index 4b94bb6..66f0f72 100644
--- a/Source/kwsys/testSystemTools.h.in
+++ b/Source/kwsys/testSystemTools.h.in
@@ -14,7 +14,8 @@
 
 #define EXECUTABLE_OUTPUT_PATH "@CMAKE_CURRENT_BINARY_DIR@"
 
-#define TEST_SYSTEMTOOLS_BIN_FILE "@TEST_SYSTEMTOOLS_BIN_FILE@"
-#define TEST_SYSTEMTOOLS_SRC_FILE "@TEST_SYSTEMTOOLS_SRC_FILE@"
+#define TEST_SYSTEMTOOLS_SOURCE_DIR "@TEST_SYSTEMTOOLS_SOURCE_DIR@"
+#define TEST_SYSTEMTOOLS_BINARY_DIR "@TEST_SYSTEMTOOLS_BINARY_DIR@"
+#cmakedefine KWSYS_TEST_SYSTEMTOOLS_LONG_PATHS
 
 #endif
diff --git a/Templates/TestDriver.cxx.in b/Templates/TestDriver.cxx.in
index 0e0a872..ffa6999 100644
--- a/Templates/TestDriver.cxx.in
+++ b/Templates/TestDriver.cxx.in
@@ -3,6 +3,10 @@
 #include <string.h>
 #include <stdlib.h>
 
+#if defined(_MSC_VER)
+# pragma warning(disable:4996) /* deprecation */
+#endif
+
 @CMAKE_TESTDRIVER_EXTRA_INCLUDES@
 
 
diff --git a/Templates/Windows/ApplicationIcon.png b/Templates/Windows/ApplicationIcon.png
new file mode 100644
index 0000000..7d95d4e
--- /dev/null
+++ b/Templates/Windows/ApplicationIcon.png
Binary files differ
diff --git a/Templates/Windows/Logo.png b/Templates/Windows/Logo.png
new file mode 100644
index 0000000..e26771c
--- /dev/null
+++ b/Templates/Windows/Logo.png
Binary files differ
diff --git a/Templates/Windows/SmallLogo.png b/Templates/Windows/SmallLogo.png
new file mode 100644
index 0000000..1eb0d9d
--- /dev/null
+++ b/Templates/Windows/SmallLogo.png
Binary files differ
diff --git a/Templates/Windows/SplashScreen.png b/Templates/Windows/SplashScreen.png
new file mode 100644
index 0000000..c951e03
--- /dev/null
+++ b/Templates/Windows/SplashScreen.png
Binary files differ
diff --git a/Templates/Windows/StoreLogo.png b/Templates/Windows/StoreLogo.png
new file mode 100644
index 0000000..dcb6727
--- /dev/null
+++ b/Templates/Windows/StoreLogo.png
Binary files differ
diff --git a/Templates/Windows/Windows_TemporaryKey.pfx b/Templates/Windows/Windows_TemporaryKey.pfx
new file mode 100644
index 0000000..1cad999
--- /dev/null
+++ b/Templates/Windows/Windows_TemporaryKey.pfx
Binary files differ
diff --git a/Tests/BundleUtilities/CMakeLists.txt b/Tests/BundleUtilities/CMakeLists.txt
index 3a1cf55..69ef535 100644
--- a/Tests/BundleUtilities/CMakeLists.txt
+++ b/Tests/BundleUtilities/CMakeLists.txt
@@ -109,7 +109,8 @@
   target_link_libraries(testbundleutils3 shared-3 framework-3 ${CMAKE_DL_LIBS})
 
   set_target_properties(testbundleutils3 module3 PROPERTIES
-                        LINK_FLAGS "-Wl,-rpath,@loader_path/")
+                        LINK_FLAGS "-Wl,-rpath,@loader_path/"
+                        BUILD_WITH_INSTALL_RPATH 1)
 
   # add custom target to install and test the app
   add_custom_target(testbundleutils3_test  ALL
diff --git a/Tests/CMakeBuildTest.cmake.in b/Tests/CMakeBuildTest.cmake.in
index aaefe43..71bcb18 100644
--- a/Tests/CMakeBuildTest.cmake.in
+++ b/Tests/CMakeBuildTest.cmake.in
@@ -12,6 +12,7 @@
 execute_process(COMMAND "${CMAKE_COMMAND}"
   "@CMAKE_BUILD_TEST_SOURCE_DIR@"
   "-G@CMAKE_GENERATOR@"
+  -A "@CMAKE_GENERATOR_PLATFORM@"
   -T "@CMAKE_GENERATOR_TOOLSET@"
   WORKING_DIRECTORY "@CMAKE_BUILD_TEST_BINARY_DIR@"
   RESULT_VARIABLE RESULT)
diff --git a/Tests/CMakeLists.txt b/Tests/CMakeLists.txt
index 3e69f93..25cc846 100644
--- a/Tests/CMakeLists.txt
+++ b/Tests/CMakeLists.txt
@@ -3,7 +3,7 @@
 macro(ADD_TEST_MACRO NAME COMMAND)
   string(REPLACE "." "/" dir "${NAME}")
   string(REGEX REPLACE "[^.]*\\." "" proj "${NAME}")
-  add_test(${NAME} ${CMAKE_CTEST_COMMAND}
+  add_test(NAME "${NAME}" COMMAND "${CMAKE_CTEST_COMMAND}"
     --build-and-test
     "${CMake_SOURCE_DIR}/Tests/${dir}"
     "${CMake_BINARY_DIR}/Tests/${dir}"
@@ -77,7 +77,7 @@
   # some old versions of make simply cannot handle spaces in paths
   if (MAKE_IS_GNU OR
       CMAKE_MAKE_PROGRAM MATCHES "nmake|gmake|wmake" OR
-      CMAKE_GENERATOR MATCHES "Visual Studio|XCode|Borland")
+      CMAKE_GENERATOR MATCHES "Visual Studio|Xcode|Borland")
     set(MAKE_SUPPORTS_SPACES 1)
   else()
     set(MAKE_SUPPORTS_SPACES 0)
@@ -86,6 +86,11 @@
   set(build_generator_args
     --build-generator ${CMAKE_GENERATOR}
     )
+  if(CMAKE_GENERATOR_PLATFORM)
+    list(APPEND build_generator_args
+      --build-generator-platform ${CMAKE_GENERATOR_PLATFORM}
+      )
+  endif()
   if(CMAKE_GENERATOR_TOOLSET)
     list(APPEND build_generator_args
       --build-generator-toolset ${CMAKE_GENERATOR_TOOLSET}
@@ -508,6 +513,7 @@
          "${CMake_BINARY_DIR}/Tests/Simple_EclipseGenerator"
          --build-two-config
          --build-generator "Eclipse CDT4 - Unix Makefiles"
+         --build-generator-platform "${CMAKE_GENERATOR_PLATFORM}"
          --build-generator-toolset "${CMAKE_GENERATOR_TOOLSET}"
          --build-project Simple
          --build-options ${build_options}
@@ -523,6 +529,7 @@
          "${CMake_BINARY_DIR}/Tests/Simple_CodeBlocksGenerator"
          --build-two-config
          --build-generator "CodeBlocks - Unix Makefiles"
+         --build-generator-platform "${CMAKE_GENERATOR_PLATFORM}"
          --build-generator-toolset "${CMAKE_GENERATOR_TOOLSET}"
          --build-project Simple
          --build-options ${build_options}
@@ -537,6 +544,7 @@
          "${CMake_BINARY_DIR}/Tests/Simple_KDevelop3Generator"
          --build-two-config
          --build-generator "KDevelop3 - Unix Makefiles"
+         --build-generator-platform "${CMAKE_GENERATOR_PLATFORM}"
          --build-generator-toolset "${CMAKE_GENERATOR_TOOLSET}"
          --build-project Simple
          --build-options ${build_options}
@@ -577,6 +585,7 @@
       "${CMake_SOURCE_DIR}/Tests/SubProject/foo"
       "${CMake_BINARY_DIR}/Tests/SubProject/foo"
       --build-generator ${CMAKE_GENERATOR}
+      --build-generator-platform "${CMAKE_GENERATOR_PLATFORM}"
       --build-generator-toolset "${CMAKE_GENERATOR_TOOLSET}"
       ${SubProject-Stage2_BUILD_MAKEPROGRAM}
       --build-nocmake
@@ -863,6 +872,10 @@
           "-DCPackWiXGenerator_BINARY_DIR:PATH=${CMake_BINARY_DIR}/Tests/CPackWiXGenerator"
           "-Dconfig=\${CTEST_CONFIGURATION_TYPE}"
           -P "${CMake_SOURCE_DIR}/Tests/CPackWiXGenerator/RunCPackVerifyResult.cmake")
+
+      set_property(TEST CPackWiXGenerator PROPERTY
+        ATTACHED_FILES_ON_FAIL
+        "${CMake_BINARY_DIR}/Tests/CPackWiXGenerator/_CPack_Packages/win32/WIX/wix.log")
     endif()
   endif()
 
@@ -1249,6 +1262,21 @@
   set_tests_properties(ExternalProject PROPERTIES
     TIMEOUT ${CMAKE_LONG_TEST_TIMEOUT})
 
+  add_test(ExternalProjectLocal ${CMAKE_CTEST_COMMAND}
+    --build-and-test
+    "${CMake_SOURCE_DIR}/Tests/ExternalProjectLocal"
+    "${CMake_BINARY_DIR}/Tests/ExternalProjectLocal"
+    ${build_generator_args}
+    --build-project ExternalProjectLocalTest
+    --build-exe-dir "${CMake_BINARY_DIR}/Tests/ExternalProjectLocal"
+    --force-new-ctest-process
+    --build-options ${build_options}
+    --test-command ${CMAKE_CTEST_COMMAND} -V
+    )
+  list(APPEND TEST_BUILD_DIRS "${CMake_BINARY_DIR}/Tests/ExternalProjectLocal")
+  set_tests_properties(ExternalProjectLocal PROPERTIES
+    TIMEOUT ${CMAKE_LONG_TEST_TIMEOUT})
+
   add_test(ExternalProjectUpdateSetup ${CMAKE_CTEST_COMMAND}
     --build-and-test
     "${CMake_SOURCE_DIR}/Tests/ExternalProjectUpdate"
@@ -1269,6 +1297,7 @@
     -DExternalProjectUpdate_SOURCE_DIR:PATH=${CMake_SOURCE_DIR}/Tests/ExternalProjectUpdate
     -DExternalProjectUpdate_BINARY_DIR:PATH=${CMake_BINARY_DIR}/Tests/ExternalProjectUpdate
     -DCMAKE_GENERATOR=${CMAKE_GENERATOR}
+    -DCMAKE_GENERATOR_PLATFORM=${CMAKE_GENERATOR_PLATFORM}
     -DCMAKE_GENERATOR_TOOLSET=${CMAKE_GENERATOR_TOOLSET}
     -DCMAKE_CTEST_COMMAND=${CMAKE_CTEST_COMMAND}
     -P ${CMake_SOURCE_DIR}/Tests/ExternalProjectUpdate/ExternalProjectUpdateTest.cmake
@@ -1373,7 +1402,7 @@
     )
   list(APPEND TEST_BUILD_DIRS "${CMake_BINARY_DIR}/Tests/Dependency")
 
-  if("${CMAKE_SYSTEM_NAME}" MATCHES syllable)
+  if(CMAKE_SYSTEM_NAME MATCHES syllable)
 
 # RPATH isn't supported under Syllable, so the tests don't
 # find their libraries. In order to fix that LIBRARY_OUTPUT_DIR
@@ -1487,7 +1516,7 @@
       )
   endif()
 
-  if(MAKE_SUPPORTS_SPACES)
+  if(MAKE_SUPPORTS_SPACES AND NOT CMAKE_GENERATOR STREQUAL "Xcode")
     add_test(SubDirSpaces ${CMAKE_CTEST_COMMAND}
       --build-and-test
       "${CMake_SOURCE_DIR}/Tests/SubDirSpaces"
@@ -1664,6 +1693,14 @@
     list(APPEND TEST_BUILD_DIRS "${CMake_BINARY_DIR}/Tests/MFC")
   endif()
 
+  if(MSVC AND NOT MSVC_VERSION LESS 1310
+     AND NOT CMAKE_GENERATOR MATCHES "Visual Studio [67]( |$)"
+     AND (NOT CMAKE_GENERATOR MATCHES "Visual Studio [89]( |$)"
+          OR CMAKE_SIZEOF_VOID_P EQUAL 4)
+      )
+    ADD_TEST_MACRO(VSMASM VSMASM)
+  endif()
+
   if(${CMAKE_GENERATOR} MATCHES "Visual Studio")
     if(NOT MSVC60)
       ADD_TEST_MACRO(SBCS SBCS)
@@ -1710,6 +1747,7 @@
           --build-two-config
           --build-generator ${CMAKE_GENERATOR}
           --build-makeprogram ${CMake_TEST_DEVENV}
+          --build-generator-platform "${CMAKE_GENERATOR_PLATFORM}"
           --build-generator-toolset "${CMAKE_GENERATOR_TOOLSET}"
           --build-project VSExcludeFromDefaultBuild
           --test-command ${CMAKE_COMMAND}
@@ -1734,6 +1772,7 @@
         "${CMake_BINARY_DIR}/Tests/VSProjectInSubdir"
         --build-two-config
         --build-generator ${CMAKE_GENERATOR}
+        --build-generator-platform "${CMAKE_GENERATOR_PLATFORM}"
         --build-generator-toolset "${CMAKE_GENERATOR_TOOLSET}"
         --build-project VSProjectInSubdir
         --build-target test)
@@ -1741,6 +1780,85 @@
     endif()
   endif()
 
+  if(WIN32)
+    set(reg_vs10 "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\10.0;InstallDir]")
+    set(reg_vs11 "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\11.0;InstallDir]")
+    set(reg_vs12 "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\12.0;InstallDir]")
+    set(reg_ws80 "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\v8.0;InstallationFolder]")
+    set(reg_ws81 "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\v8.1;InstallationFolder]")
+    set(reg_wp80 "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Microsoft SDKs\\WindowsPhone\\v8.0;InstallationFolder]")
+    set(reg_wp81 "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Microsoft SDKs\\WindowsPhone\\v8.1;InstallationFolder]")
+    set(reg_tegra "[HKEY_LOCAL_MACHINE\\SOFTWARE\\NVIDIA Corporation\\Nsight Tegra;sdkRoot]")
+    foreach(reg vs10 vs11 vs12 ws80 ws81 wp80 wp81 tegra)
+      get_filename_component(r "${reg_${reg}}" ABSOLUTE)
+      if(IS_DIRECTORY "${r}")
+        set(${reg} 1)
+      else()
+        set(${reg} 0)
+      endif()
+    endforeach()
+  endif()
+
+  get_filename_component(ntver "[HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows NT\\CurrentVersion;CurrentVersion]" NAME)
+  if(WIN32 AND ntver VERSION_GREATER 6.1) # Windows >= 8.0
+    macro(add_test_VSWinStorePhone name generator systemName systemVersion)
+      add_test(NAME VSWinStorePhone.${name} COMMAND ${CMAKE_CTEST_COMMAND}
+        --build-and-test
+        "${CMake_SOURCE_DIR}/Tests/VSWinStorePhone"
+        "${CMake_BINARY_DIR}/Tests/VSWinStorePhone/${name}"
+        --build-generator "${generator}"
+        --build-project VSWinStorePhone
+        --build-config $<CONFIGURATION>
+        --build-options -DCMAKE_SYSTEM_NAME=${systemName}
+                        -DCMAKE_SYSTEM_VERSION=${systemVersion}
+        )
+      list(APPEND TEST_BUILD_DIRS "${CMake_BINARY_DIR}/Tests/VSWinStorePhone/${name}")
+    endmacro()
+
+    if(vs11 AND ws80)
+      add_test_VSWinStorePhone(vs11-store80-X86 "Visual Studio 11 2012" WindowsStore 8.0)
+      add_test_VSWinStorePhone(vs11-store80-ARM "Visual Studio 11 2012 ARM" WindowsStore 8.0)
+      add_test_VSWinStorePhone(vs11-store80-X64 "Visual Studio 11 2012 Win64" WindowsStore 8.0)
+    endif()
+    if(vs12 AND ws81)
+      add_test_VSWinStorePhone(vs12-store81-X86 "Visual Studio 12 2013" WindowsStore 8.1)
+      add_test_VSWinStorePhone(vs12-store81-ARM "Visual Studio 12 2013 ARM" WindowsStore 8.1)
+      add_test_VSWinStorePhone(vs12-store81-X64 "Visual Studio 12 2013 Win64" WindowsStore 8.1)
+    endif()
+    if(vs11 AND wp80)
+      add_test_VSWinStorePhone(vs11-phone80-X86 "Visual Studio 11 2012" WindowsPhone 8.0)
+      add_test_VSWinStorePhone(vs11-phone80-ARM "Visual Studio 11 2012 ARM" WindowsPhone 8.0)
+    endif()
+    if(vs12 AND wp81)
+      add_test_VSWinStorePhone(vs12-phone81-X86 "Visual Studio 12 2013" WindowsPhone 8.1)
+      add_test_VSWinStorePhone(vs12-phone81-ARM "Visual Studio 12 2013 ARM" WindowsPhone 8.1)
+    endif()
+  endif()
+
+  if(tegra AND NOT "${CMake_SOURCE_DIR};${CMake_BINARY_DIR}" MATCHES " ")
+    macro(add_test_VSNsightTegra name generator)
+      add_test(NAME VSNsightTegra.${name} COMMAND ${CMAKE_CTEST_COMMAND}
+        --build-and-test
+        "${CMake_SOURCE_DIR}/Tests/VSNsightTegra"
+        "${CMake_BINARY_DIR}/Tests/VSNsightTegra/${name}"
+        --build-generator "${generator}"
+        --build-project VSNsightTegra
+        --build-config $<CONFIGURATION>
+        --build-options -DCMAKE_SYSTEM_NAME=Android
+        )
+      list(APPEND TEST_BUILD_DIRS "${CMake_BINARY_DIR}/Tests/VSNsightTegra/${name}")
+    endmacro()
+    if(vs10)
+      add_test_VSNsightTegra(vs10 "Visual Studio 10 2010")
+    endif()
+    if(vs11)
+      add_test_VSNsightTegra(vs11 "Visual Studio 11 2012")
+    endif()
+    if(vs12)
+      add_test_VSNsightTegra(vs12 "Visual Studio 12 2013")
+    endif()
+  endif()
+
   if (APPLE)
     if (CMAKE_COMPILER_IS_GNUCXX OR "${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang")
       set(BundleTestInstallDir
@@ -1898,6 +2016,9 @@
 
   # A test for ctest_build() with targets in subdirectories
   set(ctest_configure_options)
+  if(CMAKE_GENERATOR_PLATFORM)
+    list(APPEND ctest_configure_options -A ${CMAKE_GENERATOR_PLATFORM})
+  endif()
   if(CMAKE_GENERATOR_TOOLSET)
     list(APPEND ctest_configure_options -T ${CMAKE_GENERATOR_TOOLSET})
   endif()
@@ -2145,7 +2266,7 @@
     $<TARGET_FILE:ctest> -T Coverage --debug)
   set_tests_properties(CTestGTMCoverage PROPERTIES
       PASS_REGULAR_EXPRESSION
-      "Process file.*ZZCOVTST.m.*Total LOC:.*23.*Percentage Coverage: 82.61*"
+      "Process file.*ZZCOVTST.m.*Total LOC:.*30.*Percentage Coverage: 80.00*"
       ENVIRONMENT COVFILE=)
 
   configure_file(
@@ -2163,7 +2284,7 @@
     $<TARGET_FILE:ctest> -T Coverage --debug)
   set_tests_properties(CTestCacheCoverage PROPERTIES
       PASS_REGULAR_EXPRESSION
-      "Process file.*ZZCOVTST.m.*Total LOC:.*22.*Percentage Coverage: 86.36.*"
+      "Process file.*ZZCOVTST.m.*Total LOC:.*29.*Percentage Coverage: 86.21.*"
       ENVIRONMENT COVFILE=)
 
   # Adding a test case for Python Coverage
@@ -2202,6 +2323,22 @@
       "Process file.*CoverageTest.java.*Total LOC:.*18.*Percentage Coverage: 72.22.*"
       ENVIRONMENT COVFILE=)
 
+
+  # Adding a test case for JaCoCo Coverage
+  configure_file(
+     "${CMake_SOURCE_DIR}/Tests/JacocoCoverage/DartConfiguration.tcl.in"
+     "${CMake_BINARY_DIR}/Testing/JacocoCoverage/DartConfiguration.tcl")
+  file(COPY "${CMake_SOURCE_DIR}/Tests/JacocoCoverage/Coverage"
+    DESTINATION "${CMake_BINARY_DIR}/Testing/JacocoCoverage")
+  add_test(NAME CTestJacocoCoverage
+    COMMAND cmake -E chdir
+    ${CMake_BINARY_DIR}/Testing/JacocoCoverage
+    $<TARGET_FILE:ctest> -T Coverage --debug)
+  set_tests_properties(CTestJacocoCoverage PROPERTIES
+      PASS_REGULAR_EXPRESSION
+      "Process file.*CoverageTest.java.*Total LOC:.*17.*Percentage Coverage: 76.47*"
+      ENVIRONMENT COVFILE=)
+
   function(add_config_tests cfg)
     set(base "${CMake_BINARY_DIR}/Tests/CTestConfig")
 
@@ -2501,7 +2638,7 @@
   set(regex "${regex}|Error message was: ")
   set(regex "${regex}([Cc]ould *n.t resolve host")
   set(regex "${regex}|[Cc]ould *n.t connect to host")
-  set(regex "${regex}|Failed connect to")
+  set(regex "${regex}|Failed *t*o* connect to")
   set(regex "${regex}|Empty reply from server")
   set(regex "${regex}|The requested URL returned error")
   set(regex "${regex}|libcurl was built with SSL disabled. https: not supported)")
@@ -2533,7 +2670,7 @@
 
 
   if (CMAKE_TESTS_CDASH_SERVER)
-    set(regex "^([^:]+)://([^/]+)(/.*)$")
+    set(regex "^([^:]+)://([^/]+)(.*)$")
 
     if ("${CMAKE_TESTS_CDASH_SERVER}" MATCHES "${regex}")
       set(protocol "${CMAKE_MATCH_1}")
@@ -2541,8 +2678,8 @@
       set(path "${CMAKE_MATCH_3}")
     else ()
       set(protocol "http")
-      set(server "www.cdash.org")
-      set(path "/CDash")
+      set(server "open.cdash.org")
+      set(path "")
       message("warning: CMAKE_TESTS_CDASH_SERVER does not match expected regex...")
       message("         ...using default url='${protocol}://${server}${path}' for CTestTest[23]")
     endif ()
diff --git a/Tests/CMakeOnly/MajorVersionSelection/CMakeLists.txt b/Tests/CMakeOnly/MajorVersionSelection/CMakeLists.txt
index 74f5451..2511064 100644
--- a/Tests/CMakeOnly/MajorVersionSelection/CMakeLists.txt
+++ b/Tests/CMakeOnly/MajorVersionSelection/CMakeLists.txt
@@ -20,13 +20,13 @@
 
 string(TOUPPER "${MAJOR_TEST_MODULE}" MODULE_UPPER)
 
-if ( ( ${MAJOR_TEST_MODULE}_FOUND OR ${MODULE_UPPER}_FOUND ) AND "${VERSION_VAR}")
+if ( ( ${MAJOR_TEST_MODULE}_FOUND OR ${MODULE_UPPER}_FOUND ) AND ${VERSION_VAR})
   message(STATUS "${VERSION_VAR} is '${${VERSION_VAR}}'")
-  if ("${VERSION_VAR}" VERSION_LESS MAJOR_TEST_VERSION)
+  if (${VERSION_VAR} VERSION_LESS MAJOR_TEST_VERSION)
     message(SEND_ERROR "Found version ${${VERSION_VAR}} is less than requested major version ${MAJOR_TEST_VERSION}")
   endif ()
   math(EXPR V_PLUS_ONE "${MAJOR_TEST_VERSION} + 1")
-  if ("${VERSION_VAR}" VERSION_GREATER V_PLUS_ONE)
+  if (${VERSION_VAR} VERSION_GREATER V_PLUS_ONE)
     message(SEND_ERROR "Found version ${${VERSION_VAR}} is greater than requested major version ${MAJOR_TEST_VERSION}")
   endif ()
 endif ()
diff --git a/Tests/CMakeOnly/Test.cmake.in b/Tests/CMakeOnly/Test.cmake.in
index 285643a..8d3258b 100644
--- a/Tests/CMakeOnly/Test.cmake.in
+++ b/Tests/CMakeOnly/Test.cmake.in
@@ -9,6 +9,7 @@
 execute_process(
   COMMAND  ${CMAKE_COMMAND} ${CMAKE_ARGS}
   "${source_dir}" -G "@CMAKE_GENERATOR@"
+  -A "@CMAKE_GENERATOR_PLATFORM@"
   -T "@CMAKE_GENERATOR_TOOLSET@"
   WORKING_DIRECTORY "${binary_dir}"
   RESULT_VARIABLE result
diff --git a/Tests/CTestConfig/dashboard.cmake.in b/Tests/CTestConfig/dashboard.cmake.in
index 608501c..143fe71 100644
--- a/Tests/CTestConfig/dashboard.cmake.in
+++ b/Tests/CTestConfig/dashboard.cmake.in
@@ -19,6 +19,7 @@
 execute_process(COMMAND ${CMAKE_COMMAND}
    ${arg}
    -G "@CMAKE_GENERATOR@"
+   -A "@CMAKE_GENERATOR_PLATFORM@"
    -T "@CMAKE_GENERATOR_TOOLSET@"
    ${CTEST_SOURCE_DIRECTORY}
   WORKING_DIRECTORY ${CTEST_BINARY_DIRECTORY}
diff --git a/Tests/CTestConfig/script.cmake.in b/Tests/CTestConfig/script.cmake.in
index 166de3b..b6ccedb 100644
--- a/Tests/CTestConfig/script.cmake.in
+++ b/Tests/CTestConfig/script.cmake.in
@@ -1,4 +1,5 @@
 set(CTEST_CMAKE_GENERATOR "@CMAKE_GENERATOR@")
+set(CTEST_CMAKE_GENERATOR_PLATFORM "@CMAKE_GENERATOR_PLATFORM@")
 set(CTEST_CMAKE_GENERATOR_TOOLSET "@CMAKE_GENERATOR_TOOLSET@")
 set(CTEST_PROJECT_NAME "CTestConfig")
 set(CTEST_SOURCE_DIRECTORY "@CMake_SOURCE_DIR@/Tests/CTestConfig")
diff --git a/Tests/CTestTest/test.cmake.in b/Tests/CTestTest/test.cmake.in
index ab39b88..bb6346b 100644
--- a/Tests/CTestTest/test.cmake.in
+++ b/Tests/CTestTest/test.cmake.in
@@ -41,6 +41,7 @@
 SITE:STRING=@SITE@
 BUILDNAME:STRING=SmallAndFast-@BUILDNAME@
 CMAKE_GENERATOR:INTERNAL=@CMAKE_GENERATOR@
+CMAKE_GENERATOR_PLATFORM:INTERNAL=@CMAKE_GENERATOR_PLATFORM@
 CMAKE_GENERATOR_TOOLSET:INTERNAL=@CMAKE_GENERATOR_TOOLSET@
 CMAKE_CXX_FLAGS:STRING=@CMAKE_CXX_FLAGS@
 CMAKE_C_FLAGS:STRING=@CMAKE_C_FLAGS@
diff --git a/Tests/CTestTest2/test.cmake.in b/Tests/CTestTest2/test.cmake.in
index c5a7b45..852bb6b 100644
--- a/Tests/CTestTest2/test.cmake.in
+++ b/Tests/CTestTest2/test.cmake.in
@@ -9,6 +9,7 @@
 set(CTEST_BINARY_DIRECTORY              "@CMake_BINARY_DIR@/Tests/CTestTest2/kwsysBin")
 set(CTEST_CVS_COMMAND                   "@CVSCOMMAND@")
 set(CTEST_CMAKE_GENERATOR               "@CMAKE_GENERATOR@")
+set(CTEST_CMAKE_GENERATOR_PLATFORM      "@CMAKE_GENERATOR_PLATFORM@")
 set(CTEST_CMAKE_GENERATOR_TOOLSET       "@CMAKE_GENERATOR_TOOLSET@")
 set(CTEST_BUILD_CONFIGURATION           "$ENV{CMAKE_CONFIG_TYPE}")
 set(CTEST_MEMORYCHECK_COMMAND           "@MEMORYCHECK_COMMAND@")
diff --git a/Tests/CTestTestBadExe/CTestConfig.cmake b/Tests/CTestTestBadExe/CTestConfig.cmake
index 1d46ea3..c7286e2 100644
--- a/Tests/CTestTestBadExe/CTestConfig.cmake
+++ b/Tests/CTestTestBadExe/CTestConfig.cmake
@@ -2,6 +2,6 @@
 set (CTEST_NIGHTLY_START_TIME "21:00:00 EDT")
 set (CTEST_DART_SERVER_VERSION "2")
 set(CTEST_DROP_METHOD "http")
-set(CTEST_DROP_SITE "www.cdash.org")
-set(CTEST_DROP_LOCATION "/CDash/submit.php?project=PublicDashboard")
+set(CTEST_DROP_SITE "open.cdash.org")
+set(CTEST_DROP_LOCATION "/submit.php?project=PublicDashboard")
 set(CTEST_DROP_SITE_CDASH TRUE)
diff --git a/Tests/CTestTestBadExe/test.cmake.in b/Tests/CTestTestBadExe/test.cmake.in
index 601aab4..43a8572 100644
--- a/Tests/CTestTestBadExe/test.cmake.in
+++ b/Tests/CTestTestBadExe/test.cmake.in
@@ -9,6 +9,7 @@
 set(CTEST_BINARY_DIRECTORY              "@CMake_BINARY_DIR@/Tests/CTestTestBadExe")
 set(CTEST_CVS_COMMAND                   "@CVSCOMMAND@")
 set(CTEST_CMAKE_GENERATOR               "@CMAKE_GENERATOR@")
+set(CTEST_CMAKE_GENERATOR_PLATFORM      "@CMAKE_GENERATOR_PLATFORM@")
 set(CTEST_CMAKE_GENERATOR_TOOLSET       "@CMAKE_GENERATOR_TOOLSET@")
 set(CTEST_BUILD_CONFIGURATION           "$ENV{CMAKE_CONFIG_TYPE}")
 set(CTEST_COVERAGE_COMMAND              "@COVERAGE_COMMAND@")
diff --git a/Tests/CTestTestBadGenerator/CTestConfig.cmake b/Tests/CTestTestBadGenerator/CTestConfig.cmake
index ef98189..1e61bf4 100644
--- a/Tests/CTestTestBadGenerator/CTestConfig.cmake
+++ b/Tests/CTestTestBadGenerator/CTestConfig.cmake
@@ -2,6 +2,6 @@
 set (CTEST_NIGHTLY_START_TIME "21:00:00 EDT")
 set (CTEST_DART_SERVER_VERSION "2")
 set(CTEST_DROP_METHOD "http")
-set(CTEST_DROP_SITE "www.cdash.org")
-set(CTEST_DROP_LOCATION "/CDash/submit.php?project=PublicDashboard")
+set(CTEST_DROP_SITE "open.cdash.org")
+set(CTEST_DROP_LOCATION "/submit.php?project=PublicDashboard")
 set(CTEST_DROP_SITE_CDASH TRUE)
diff --git a/Tests/CTestTestBadGenerator/test.cmake.in b/Tests/CTestTestBadGenerator/test.cmake.in
index fe4fba8..ae6d0b5 100644
--- a/Tests/CTestTestBadGenerator/test.cmake.in
+++ b/Tests/CTestTestBadGenerator/test.cmake.in
@@ -9,6 +9,7 @@
 set(CTEST_BINARY_DIRECTORY              "@CMake_BINARY_DIR@/Tests/CTestTestBadGenerator")
 set(CTEST_CVS_COMMAND                   "@CVSCOMMAND@")
 set(CTEST_CMAKE_GENERATOR               "Bad Generator")
+set(CTEST_CMAKE_GENERATOR_PLATFORM      "")
 set(CTEST_CMAKE_GENERATOR_TOOLSET       "")
 set(CTEST_BUILD_CONFIGURATION           "$ENV{CMAKE_CONFIG_TYPE}")
 set(CTEST_COVERAGE_COMMAND              "@COVERAGE_COMMAND@")
diff --git a/Tests/CTestTestChecksum/test.cmake.in b/Tests/CTestTestChecksum/test.cmake.in
index 8413443..32d62bb 100644
--- a/Tests/CTestTestChecksum/test.cmake.in
+++ b/Tests/CTestTestChecksum/test.cmake.in
@@ -9,6 +9,7 @@
 set(CTEST_BINARY_DIRECTORY              "@CMake_BINARY_DIR@/Tests/CTestTestParallel")
 set(CTEST_CVS_COMMAND                   "@CVSCOMMAND@")
 set(CTEST_CMAKE_GENERATOR               "@CMAKE_GENERATOR@")
+set(CTEST_CMAKE_GENERATOR_PLATFORM      "@CMAKE_GENERATOR_PLATFORM@")
 set(CTEST_CMAKE_GENERATOR_TOOLSET       "@CMAKE_GENERATOR_TOOLSET@")
 set(CTEST_BUILD_CONFIGURATION           "$ENV{CMAKE_CONFIG_TYPE}")
 set(CTEST_COVERAGE_COMMAND              "@COVERAGE_COMMAND@")
diff --git a/Tests/CTestTestConfigFileInBuildDir/CTestConfig.cmake b/Tests/CTestTestConfigFileInBuildDir/CTestConfig.cmake
index d2c28f9..4458348 100644
--- a/Tests/CTestTestConfigFileInBuildDir/CTestConfig.cmake
+++ b/Tests/CTestTestConfigFileInBuildDir/CTestConfig.cmake
@@ -2,6 +2,6 @@
 set(CTEST_NIGHTLY_START_TIME "01:00:00 UTC")
 set(CTEST_DART_SERVER_VERSION "2")
 set(CTEST_DROP_METHOD "http")
-set(CTEST_DROP_SITE "www.cdash.org")
-set(CTEST_DROP_LOCATION "/CDash/submit.php?project=PublicDashboard")
+set(CTEST_DROP_SITE "open.cdash.org")
+set(CTEST_DROP_LOCATION "/submit.php?project=PublicDashboard")
 set(CTEST_DROP_SITE_CDASH TRUE)
diff --git a/Tests/CTestTestConfigFileInBuildDir/test1.cmake.in b/Tests/CTestTestConfigFileInBuildDir/test1.cmake.in
index d3510bb..6d29af7 100644
--- a/Tests/CTestTestConfigFileInBuildDir/test1.cmake.in
+++ b/Tests/CTestTestConfigFileInBuildDir/test1.cmake.in
@@ -9,6 +9,7 @@
 set(CTEST_BINARY_DIRECTORY              "@CMake_BINARY_DIR@/Tests/CTestTestConfigFileInBuildDir1")
 set(CTEST_CVS_COMMAND                   "@CVSCOMMAND@")
 set(CTEST_CMAKE_GENERATOR               "@CMAKE_GENERATOR@")
+set(CTEST_CMAKE_GENERATOR_PLATFORM      "@CMAKE_GENERATOR_PLATFORM@")
 set(CTEST_CMAKE_GENERATOR_TOOLSET       "@CMAKE_GENERATOR_TOOLSET@")
 set(CTEST_BUILD_CONFIGURATION           "$ENV{CMAKE_CONFIG_TYPE}")
 set(CTEST_COVERAGE_COMMAND              "@COVERAGE_COMMAND@")
diff --git a/Tests/CTestTestConfigFileInBuildDir/test2.cmake.in b/Tests/CTestTestConfigFileInBuildDir/test2.cmake.in
index 99b002c..fb298d4 100644
--- a/Tests/CTestTestConfigFileInBuildDir/test2.cmake.in
+++ b/Tests/CTestTestConfigFileInBuildDir/test2.cmake.in
@@ -9,6 +9,7 @@
 set(CTEST_BINARY_DIRECTORY              "@CMake_BINARY_DIR@/Tests/CTestTestConfigFileInBuildDir2")
 set(CTEST_CVS_COMMAND                   "@CVSCOMMAND@")
 set(CTEST_CMAKE_GENERATOR               "@CMAKE_GENERATOR@")
+set(CTEST_CMAKE_GENERATOR_PLATFORM      "@CMAKE_GENERATOR_PLATFORM@")
 set(CTEST_CMAKE_GENERATOR_TOOLSET       "@CMAKE_GENERATOR_TOOLSET@")
 set(CTEST_BUILD_CONFIGURATION           "$ENV{CMAKE_CONFIG_TYPE}")
 set(CTEST_COVERAGE_COMMAND              "@COVERAGE_COMMAND@")
diff --git a/Tests/CTestTestCostSerial/CTestConfig.cmake b/Tests/CTestTestCostSerial/CTestConfig.cmake
index 05c20eb..3ab99ac 100644
--- a/Tests/CTestTestCostSerial/CTestConfig.cmake
+++ b/Tests/CTestTestCostSerial/CTestConfig.cmake
@@ -2,6 +2,6 @@
 set(CTEST_NIGHTLY_START_TIME "21:00:00 EDT")
 set(CTEST_DART_SERVER_VERSION "2")
 set(CTEST_DROP_METHOD "http")
-set(CTEST_DROP_SITE "www.cdash.org")
-set(CTEST_DROP_LOCATION "/CDash/submit.php?project=PublicDashboard")
+set(CTEST_DROP_SITE "open.cdash.org")
+set(CTEST_DROP_LOCATION "/submit.php?project=PublicDashboard")
 set(CTEST_DROP_SITE_CDASH TRUE)
diff --git a/Tests/CTestTestCostSerial/test.cmake.in b/Tests/CTestTestCostSerial/test.cmake.in
index ce8720c..9b32a46 100644
--- a/Tests/CTestTestCostSerial/test.cmake.in
+++ b/Tests/CTestTestCostSerial/test.cmake.in
@@ -9,6 +9,7 @@
 set(CTEST_BINARY_DIRECTORY              "@CMake_BINARY_DIR@/Tests/CTestTestCostSerial")
 set(CTEST_CVS_COMMAND                   "@CVSCOMMAND@")
 set(CTEST_CMAKE_GENERATOR               "@CMAKE_GENERATOR@")
+set(CTEST_CMAKE_GENERATOR_PLATFORM      "@CMAKE_GENERATOR_PLATFORM@")
 set(CTEST_CMAKE_GENERATOR_TOOLSET       "@CMAKE_GENERATOR_TOOLSET@")
 set(CTEST_BUILD_CONFIGURATION           "$ENV{CMAKE_CONFIG_TYPE}")
 set(CTEST_COVERAGE_COMMAND              "@COVERAGE_COMMAND@")
diff --git a/Tests/CTestTestCrash/CTestConfig.cmake b/Tests/CTestTestCrash/CTestConfig.cmake
index e1c5b1b..5c2ca0e 100644
--- a/Tests/CTestTestCrash/CTestConfig.cmake
+++ b/Tests/CTestTestCrash/CTestConfig.cmake
@@ -2,6 +2,6 @@
 set (CTEST_NIGHTLY_START_TIME "21:00:00 EDT")
 set (CTEST_DART_SERVER_VERSION "2")
 set(CTEST_DROP_METHOD "http")
-set(CTEST_DROP_SITE "www.cdash.org")
-set(CTEST_DROP_LOCATION "/CDash/submit.php?project=PublicDashboard")
+set(CTEST_DROP_SITE "open.cdash.org")
+set(CTEST_DROP_LOCATION "/submit.php?project=PublicDashboard")
 set(CTEST_DROP_SITE_CDASH TRUE)
diff --git a/Tests/CTestTestCrash/test.cmake.in b/Tests/CTestTestCrash/test.cmake.in
index 5906d12..3641cb0 100644
--- a/Tests/CTestTestCrash/test.cmake.in
+++ b/Tests/CTestTestCrash/test.cmake.in
@@ -9,6 +9,7 @@
 set(CTEST_BINARY_DIRECTORY              "@CMake_BINARY_DIR@/Tests/CTestTestCrash")
 set(CTEST_CVS_COMMAND                   "@CVSCOMMAND@")
 set(CTEST_CMAKE_GENERATOR               "@CMAKE_GENERATOR@")
+set(CTEST_CMAKE_GENERATOR_PLATFORM      "@CMAKE_GENERATOR_PLATFORM@")
 set(CTEST_CMAKE_GENERATOR_TOOLSET       "@CMAKE_GENERATOR_TOOLSET@")
 set(CTEST_BUILD_CONFIGURATION           "$ENV{CMAKE_CONFIG_TYPE}")
 set(CTEST_COVERAGE_COMMAND              "@COVERAGE_COMMAND@")
diff --git a/Tests/CTestTestCycle/CTestConfig.cmake b/Tests/CTestTestCycle/CTestConfig.cmake
index 43e9986..8aeb09b 100644
--- a/Tests/CTestTestCycle/CTestConfig.cmake
+++ b/Tests/CTestTestCycle/CTestConfig.cmake
@@ -2,6 +2,6 @@
 set (CTEST_NIGHTLY_START_TIME "21:00:00 EDT")
 set (CTEST_DART_SERVER_VERSION "2")
 set(CTEST_DROP_METHOD "http")
-set(CTEST_DROP_SITE "www.cdash.org")
-set(CTEST_DROP_LOCATION "/CDash/submit.php?project=PublicDashboard")
+set(CTEST_DROP_SITE "open.cdash.org")
+set(CTEST_DROP_LOCATION "/submit.php?project=PublicDashboard")
 set(CTEST_DROP_SITE_CDASH TRUE)
diff --git a/Tests/CTestTestCycle/test.cmake.in b/Tests/CTestTestCycle/test.cmake.in
index 478badb..4a63dd6 100644
--- a/Tests/CTestTestCycle/test.cmake.in
+++ b/Tests/CTestTestCycle/test.cmake.in
@@ -9,6 +9,7 @@
 set(CTEST_BINARY_DIRECTORY              "@CMake_BINARY_DIR@/Tests/CTestTestCycle")
 set(CTEST_CVS_COMMAND                   "@CVSCOMMAND@")
 set(CTEST_CMAKE_GENERATOR               "@CMAKE_GENERATOR@")
+set(CTEST_CMAKE_GENERATOR_PLATFORM      "@CMAKE_GENERATOR_PLATFORM@")
 set(CTEST_CMAKE_GENERATOR_TOOLSET       "@CMAKE_GENERATOR_TOOLSET@")
 set(CTEST_BUILD_CONFIGURATION           "$ENV{CMAKE_CONFIG_TYPE}")
 set(CTEST_COVERAGE_COMMAND              "@COVERAGE_COMMAND@")
diff --git a/Tests/CTestTestDepends/CTestConfig.cmake b/Tests/CTestTestDepends/CTestConfig.cmake
index e3af7dd..7af9200 100644
--- a/Tests/CTestTestDepends/CTestConfig.cmake
+++ b/Tests/CTestTestDepends/CTestConfig.cmake
@@ -2,6 +2,6 @@
 set (CTEST_NIGHTLY_START_TIME "21:00:00 EDT")
 set (CTEST_DART_SERVER_VERSION "2")
 set(CTEST_DROP_METHOD "http")
-set(CTEST_DROP_SITE "www.cdash.org")
-set(CTEST_DROP_LOCATION "/CDash/submit.php?project=PublicDashboard")
+set(CTEST_DROP_SITE "open.cdash.org")
+set(CTEST_DROP_LOCATION "/submit.php?project=PublicDashboard")
 set(CTEST_DROP_SITE_CDASH TRUE)
diff --git a/Tests/CTestTestDepends/test.cmake.in b/Tests/CTestTestDepends/test.cmake.in
index a7de8cc..74fddb3 100644
--- a/Tests/CTestTestDepends/test.cmake.in
+++ b/Tests/CTestTestDepends/test.cmake.in
@@ -9,6 +9,7 @@
 set(CTEST_BINARY_DIRECTORY              "@CMake_BINARY_DIR@/Tests/CTestTestDepends")
 set(CTEST_CVS_COMMAND                   "@CVSCOMMAND@")
 set(CTEST_CMAKE_GENERATOR               "@CMAKE_GENERATOR@")
+set(CTEST_CMAKE_GENERATOR_PLATFORM      "@CMAKE_GENERATOR_PLATFORM@")
 set(CTEST_CMAKE_GENERATOR_TOOLSET       "@CMAKE_GENERATOR_TOOLSET@")
 set(CTEST_BUILD_CONFIGURATION           "$ENV{CMAKE_CONFIG_TYPE}")
 set(CTEST_COVERAGE_COMMAND              "@COVERAGE_COMMAND@")
diff --git a/Tests/CTestTestFailedSubmits/test.cmake.in b/Tests/CTestTestFailedSubmits/test.cmake.in
index 36a09cf..5ff836f 100644
--- a/Tests/CTestTestFailedSubmits/test.cmake.in
+++ b/Tests/CTestTestFailedSubmits/test.cmake.in
@@ -21,6 +21,7 @@
 set(CTEST_BINARY_DIRECTORY              "@build@")
 set(CTEST_CVS_COMMAND                   "@CVSCOMMAND@")
 set(CTEST_CMAKE_GENERATOR               "@CMAKE_GENERATOR@")
+set(CTEST_CMAKE_GENERATOR_PLATFORM      "@CMAKE_GENERATOR_PLATFORM@")
 set(CTEST_CMAKE_GENERATOR_TOOLSET       "@CMAKE_GENERATOR_TOOLSET@")
 set(CTEST_BUILD_CONFIGURATION           "$ENV{CMAKE_CONFIG_TYPE}")
 set(CTEST_COVERAGE_COMMAND              "@COVERAGE_COMMAND@")
diff --git a/Tests/CTestTestFailure/CTestConfig.cmake b/Tests/CTestTestFailure/CTestConfig.cmake
index fd8d97a..07e1be0 100644
--- a/Tests/CTestTestFailure/CTestConfig.cmake
+++ b/Tests/CTestTestFailure/CTestConfig.cmake
@@ -2,6 +2,6 @@
 set (CTEST_NIGHTLY_START_TIME "21:00:00 EDT")
 set (CTEST_DART_SERVER_VERSION "2")
 set(CTEST_DROP_METHOD "http")
-set(CTEST_DROP_SITE "www.cdash.org")
-set(CTEST_DROP_LOCATION "/CDash/submit.php?project=PublicDashboard")
+set(CTEST_DROP_SITE "open.cdash.org")
+set(CTEST_DROP_LOCATION "/submit.php?project=PublicDashboard")
 set(CTEST_DROP_SITE_CDASH TRUE)
diff --git a/Tests/CTestTestFailure/testNoBuild.cmake.in b/Tests/CTestTestFailure/testNoBuild.cmake.in
index 143daf8..86333af 100644
--- a/Tests/CTestTestFailure/testNoBuild.cmake.in
+++ b/Tests/CTestTestFailure/testNoBuild.cmake.in
@@ -9,6 +9,7 @@
 set(CTEST_BINARY_DIRECTORY              "@CMake_BINARY_DIR@/Tests/CTestTestFailure")
 set(CTEST_CVS_COMMAND                   "@CVSCOMMAND@")
 set(CTEST_CMAKE_GENERATOR               "@CMAKE_GENERATOR@")
+set(CTEST_CMAKE_GENERATOR_PLATFORM      "@CMAKE_GENERATOR_PLATFORM@")
 set(CTEST_CMAKE_GENERATOR_TOOLSET       "@CMAKE_GENERATOR_TOOLSET@")
 set(CTEST_BUILD_CONFIGURATION           "$ENV{CMAKE_CONFIG_TYPE}")
 set(CTEST_COVERAGE_COMMAND              "@COVERAGE_COMMAND@")
diff --git a/Tests/CTestTestFailure/testNoExe.cmake.in b/Tests/CTestTestFailure/testNoExe.cmake.in
index 11a1930..8875cee 100644
--- a/Tests/CTestTestFailure/testNoExe.cmake.in
+++ b/Tests/CTestTestFailure/testNoExe.cmake.in
@@ -9,6 +9,7 @@
 set(CTEST_BINARY_DIRECTORY              "@CMake_BINARY_DIR@/Tests/CTestTestFailure")
 set(CTEST_CVS_COMMAND                   "@CVSCOMMAND@")
 set(CTEST_CMAKE_GENERATOR               "@CMAKE_GENERATOR@")
+set(CTEST_CMAKE_GENERATOR_PLATFORM      "@CMAKE_GENERATOR_PLATFORM@")
 set(CTEST_CMAKE_GENERATOR_TOOLSET       "@CMAKE_GENERATOR_TOOLSET@")
 set(CTEST_BUILD_CONFIGURATION           "$ENV{CMAKE_CONFIG_TYPE}")
 set(CTEST_COVERAGE_COMMAND              "@COVERAGE_COMMAND@")
diff --git a/Tests/CTestTestFdSetSize/test.cmake.in b/Tests/CTestTestFdSetSize/test.cmake.in
index fbe0e82..bfe4459 100644
--- a/Tests/CTestTestFdSetSize/test.cmake.in
+++ b/Tests/CTestTestFdSetSize/test.cmake.in
@@ -9,6 +9,7 @@
 set(CTEST_BINARY_DIRECTORY              "@CMake_BINARY_DIR@/Tests/CTestTestFdSetSize")
 set(CTEST_CVS_COMMAND                   "@CVSCOMMAND@")
 set(CTEST_CMAKE_GENERATOR               "@CMAKE_GENERATOR@")
+set(CTEST_CMAKE_GENERATOR_PLATFORM      "@CMAKE_GENERATOR_PLATFORM@")
 set(CTEST_CMAKE_GENERATOR_TOOLSET       "@CMAKE_GENERATOR_TOOLSET@")
 set(CTEST_BUILD_CONFIGURATION           "$ENV{CMAKE_CONFIG_TYPE}")
 set(CTEST_COVERAGE_COMMAND              "@COVERAGE_COMMAND@")
diff --git a/Tests/CTestTestLaunchers/launcher_test_project/CTestConfig.cmake b/Tests/CTestTestLaunchers/launcher_test_project/CTestConfig.cmake
index bf404ab..669b0fb 100644
--- a/Tests/CTestTestLaunchers/launcher_test_project/CTestConfig.cmake
+++ b/Tests/CTestTestLaunchers/launcher_test_project/CTestConfig.cmake
@@ -3,6 +3,6 @@
 set(CTEST_NIGHTLY_START_TIME "21:00:00 EDT")
 set(CTEST_DART_SERVER_VERSION "2")
 set(CTEST_DROP_METHOD "http")
-set(CTEST_DROP_SITE "www.cdash.org")
-set(CTEST_DROP_LOCATION "/CDash/submit.php?project=PublicDashboard")
+set(CTEST_DROP_SITE "open.cdash.org")
+set(CTEST_DROP_LOCATION "/submit.php?project=PublicDashboard")
 set(CTEST_DROP_SITE_CDASH TRUE)
diff --git a/Tests/CTestTestLaunchers/test.cmake.in b/Tests/CTestTestLaunchers/test.cmake.in
index 43a6533..03a118a 100644
--- a/Tests/CTestTestLaunchers/test.cmake.in
+++ b/Tests/CTestTestLaunchers/test.cmake.in
@@ -9,6 +9,7 @@
 set(CTEST_SOURCE_DIRECTORY              "${CTEST_DASHBOARD_SOURCE}/launcher_test_project")
 set(CTEST_BINARY_DIRECTORY              "${CTEST_DASHBOARD_ROOT}/launcher_test_project-bin")
 set(CTEST_CMAKE_GENERATOR               "@CMAKE_GENERATOR@")
+set(CTEST_CMAKE_GENERATOR_PLATFORM      "@CMAKE_GENERATOR_PLATFORM@")
 set(CTEST_CMAKE_GENERATOR_TOOLSET       "@CMAKE_GENERATOR_TOOLSET@")
 set(CTEST_BUILD_CONFIGURATION           "$ENV{CMAKE_CONFIG_TYPE}")
 set(CTEST_NOTES_FILES                   "${CTEST_SCRIPT_DIRECTORY}/${CTEST_SCRIPT_NAME}")
diff --git a/Tests/CTestTestMemcheck/CMakeLists.txt b/Tests/CTestTestMemcheck/CMakeLists.txt
index 8984463..2023e74 100644
--- a/Tests/CTestTestMemcheck/CMakeLists.txt
+++ b/Tests/CTestTestMemcheck/CMakeLists.txt
@@ -103,6 +103,90 @@
 unset(CTEST_EXTRA_CODE)
 unset(CMAKELISTS_EXTRA_CODE)
 
+#-----------------------------------------------------------------------------
+# add ThreadSanitizer test
+set(CTEST_EXTRA_CODE
+"set(CTEST_MEMORYCHECK_COMMAND_OPTIONS \"report_bugs=1 history_size=5 exitcode=55\")
+")
+set(CMAKELISTS_EXTRA_CODE
+"add_test(NAME TestSan COMMAND \"${CMAKE_COMMAND}\"
+-P \"${CMAKE_CURRENT_SOURCE_DIR}/testThreadSanitizer.cmake\")
+")
+gen_mc_test_internal(DummyThreadSanitizer "" -DMEMCHECK_TYPE=ThreadSanitizer)
+set_tests_properties(CTestTestMemcheckDummyThreadSanitizer PROPERTIES
+    PASS_REGULAR_EXPRESSION
+    ".*Memory checking results:.*data race.* - 1.*data race on vptr .ctor/dtor vs virtual call. - 1.*heap-use-after-free - 1.*thread leak - 1.*destroy of a locked mutex - 1.*double lock of a mutex - 1.*unlock of an unlocked mutex .or by a wrong thread. - 1.*read lock of a write locked mutex - 1.*read unlock of a write locked mutex - 1.*signal-unsafe call inside of a signal - 1.*signal handler spoils errno - 1.*lock-order-inversion .potential deadlock. - 1.*")
+set(CMAKELISTS_EXTRA_CODE )
+set(CTEST_EXTRA_CODE)
+
+#-----------------------------------------------------------------------------
+# add LeakSanitizer test
+set(CTEST_EXTRA_CODE
+"set(CTEST_MEMORYCHECK_SANITIZER_OPTIONS \"simulate_sanitizer=1 report_bugs=1 history_size=5 exitcode=55\")
+")
+set(CMAKELISTS_EXTRA_CODE
+"add_test(NAME TestSan COMMAND \"${CMAKE_COMMAND}\"
+-P \"${CMAKE_CURRENT_SOURCE_DIR}/testLeakSanitizer.cmake\")
+")
+gen_mc_test_internal(DummyLeakSanitizer "" -DMEMCHECK_TYPE=AddressSanitizer)
+set(CMAKELISTS_EXTRA_CODE )
+set(CTEST_EXTRA_CODE)
+set_tests_properties(CTestTestMemcheckDummyLeakSanitizer PROPERTIES
+    PASS_REGULAR_EXPRESSION
+    ".*Memory checking results:.*Direct leak - 2.*Indirect leak - 1.*")
+
+#-----------------------------------------------------------------------------
+# add AddressSanitizer test
+set(CTEST_EXTRA_CODE
+"set(CTEST_MEMORYCHECK_SANITIZER_OPTIONS \"simulate_sanitizer=1 report_bugs=1 history_size=5 exitcode=55\")
+")
+set(CMAKELISTS_EXTRA_CODE
+"add_test(NAME TestSan COMMAND \"${CMAKE_COMMAND}\"
+-P \"${CMAKE_CURRENT_SOURCE_DIR}/testAddressSanitizer.cmake\")
+")
+gen_mc_test_internal(DummyAddressSanitizer "" -DMEMCHECK_TYPE=AddressSanitizer)
+set(CMAKELISTS_EXTRA_CODE )
+set(CTEST_EXTRA_CODE)
+set_tests_properties(CTestTestMemcheckDummyAddressSanitizer PROPERTIES
+    PASS_REGULAR_EXPRESSION
+    ".*Memory checking results:.*heap-buffer-overflow - 1.*")
+
+#-----------------------------------------------------------------------------
+# add MemorySanitizer test
+set(CTEST_EXTRA_CODE
+"set(CTEST_MEMORYCHECK_COMMAND_OPTIONS \"simulate_sanitizer=1 report_bugs=1 history_size=5 exitcode=55\")
+")
+
+set(CMAKELISTS_EXTRA_CODE
+"add_test(NAME TestSan COMMAND \"${CMAKE_COMMAND}\"
+-P \"${CMAKE_CURRENT_SOURCE_DIR}/testMemorySanitizer.cmake\")
+")
+gen_mc_test_internal(DummyMemorySanitizer "" -DMEMCHECK_TYPE=MemorySanitizer)
+set(CMAKELISTS_EXTRA_CODE )
+set(CTEST_EXTRA_CODE)
+set_tests_properties(CTestTestMemcheckDummyMemorySanitizer PROPERTIES
+    PASS_REGULAR_EXPRESSION
+    ".*Memory checking results:.*use-of-uninitialized-value - 1.*")
+
+#-----------------------------------------------------------------------------
+# add UndefinedBehaviorSanitizer test
+set(CTEST_EXTRA_CODE
+"set(CTEST_MEMORYCHECK_SANITIZER_OPTIONS \"simulate_sanitizer=1\")
+")
+
+set(CMAKELISTS_EXTRA_CODE
+"add_test(NAME TestSan COMMAND \"${CMAKE_COMMAND}\"
+-P \"${CMAKE_CURRENT_SOURCE_DIR}/testUndefinedBehaviorSanitizer.cmake\")
+")
+gen_mc_test_internal(DummyUndefinedBehaviorSanitizer "" -DMEMCHECK_TYPE=UndefinedBehaviorSanitizer)
+set(CMAKELISTS_EXTRA_CODE )
+set(CTEST_EXTRA_CODE)
+set_tests_properties(CTestTestMemcheckDummyUndefinedBehaviorSanitizer PROPERTIES
+    PASS_REGULAR_EXPRESSION
+    ".*Memory checking results:.*left shift of negative value -256 - 1.*")
+
+#-----------------------------------------------------------------------------
+
 gen_mc_test(DummyPurify "\${PSEUDO_PURIFY}")
 gen_mc_test(DummyValgrind "\${PSEUDO_VALGRIND}")
 gen_mc_test(DummyBC "\${PSEUDO_BC}")
@@ -177,7 +261,7 @@
     PASS_REGULAR_EXPRESSION "\n2/2 Test #2: RunCMakeAgain .*${ctest_and_tool_outputs}$")
 
 set_tests_properties(CTestTestMemcheckDummyBC PROPERTIES
-    PASS_REGULAR_EXPRESSION "\n1/1 MemCheck #1: RunCMake \\.+   Passed +[0-9]+.[0-9]+ sec\n\n100% tests passed, 0 tests failed out of 1\n(.*\n)?Error parsing XML in stream at line 1: no element found\n")
+    PASS_REGULAR_EXPRESSION "\n1/1 MemCheck #1: RunCMake \\.+   Passed +[0-9]+.[0-9]+ sec\n${guard_malloc_lines}\n100% tests passed, 0 tests failed out of 1\n(.*\n)?Error parsing XML in stream at line 1: no element found\n")
 
 set_tests_properties(CTestTestMemcheckDummyValgrindInvalidSupFile PROPERTIES
     PASS_REGULAR_EXPRESSION "\nCannot find memory checker suppression file: ${CTEST_ESCAPED_REALPATH_CMAKE_CURRENT_BINARY_DIR}/does-not-exist\n")
@@ -189,6 +273,7 @@
     PASS_REGULAR_EXPRESSION
     "\nMemory check project ${CTEST_ESCAPED_CMAKE_CURRENT_BINARY_DIR}/DummyValgrindTwoTargets\n.*\n *Start 1: RunCMake\n(.*\n)?Memory check command: .* \"--log-file=${CTEST_ESCAPED_CMAKE_CURRENT_BINARY_DIR}/DummyValgrindTwoTargets/Testing/Temporary/MemoryChecker.1.log\" \"-q\".*\n *Start 2: RunCMakeAgain\n(.*\n)?Memory check command: .* \"--log-file=${CTEST_ESCAPED_CMAKE_CURRENT_BINARY_DIR}/DummyValgrindTwoTargets/Testing/Temporary/MemoryChecker.2.log\" \"-q\".*\n")
 
+
 # Xcode 2.x forgets to create the output directory before linking
 # the individual architectures.
 if(CMAKE_OSX_ARCHITECTURES AND XCODE AND NOT "${XCODE_VERSION}" MATCHES "^[^12]")
diff --git a/Tests/CTestTestMemcheck/CMakeLists.txt.in b/Tests/CTestTestMemcheck/CMakeLists.txt.in
index e28e56a..d15d148 100644
--- a/Tests/CTestTestMemcheck/CMakeLists.txt.in
+++ b/Tests/CTestTestMemcheck/CMakeLists.txt.in
@@ -1,5 +1,5 @@
 cmake_minimum_required(VERSION 2.8.9)
-project(CTestTestMemcheck@SUBTEST_NAME@)
+project(CTestTestMemcheck@SUBTEST_NAME@ NONE)
 include(CTest)
 
 add_test(NAME RunCMake COMMAND "${CMAKE_COMMAND}" --version)
diff --git a/Tests/CTestTestMemcheck/CTestConfig.cmake.in b/Tests/CTestTestMemcheck/CTestConfig.cmake.in
index 6cf3782..19c76c2 100644
--- a/Tests/CTestTestMemcheck/CTestConfig.cmake.in
+++ b/Tests/CTestTestMemcheck/CTestConfig.cmake.in
@@ -2,8 +2,8 @@
 set (CTEST_NIGHTLY_START_TIME "21:00:00 EDT")
 set (CTEST_DART_SERVER_VERSION "2")
 set(CTEST_DROP_METHOD "http")
-set(CTEST_DROP_SITE "www.cdash.org")
-set(CTEST_DROP_LOCATION "/CDash/submit.php?project=PublicDashboard")
+set(CTEST_DROP_SITE "open.cdash.org")
+set(CTEST_DROP_LOCATION "/submit.php?project=PublicDashboard")
 set(CTEST_DROP_SITE_CDASH TRUE)
 
 @CTEST_EXTRA_CONFIG@
diff --git a/Tests/CTestTestMemcheck/memtester.cxx.in b/Tests/CTestTestMemcheck/memtester.cxx.in
index 55a34e3..43c0ba7 100644
--- a/Tests/CTestTestMemcheck/memtester.cxx.in
+++ b/Tests/CTestTestMemcheck/memtester.cxx.in
@@ -1,11 +1,19 @@
 #include <cmSystemTools.h>
+#include <cmsys/Encoding.hxx>
 #include <string>
+#include <locale.h>
 
 #define RETVAL @_retval@
 
 int
-main(int argc, char **argv)
+main(int ac, char **av)
 {
+  setlocale(LC_CTYPE, "");
+  cmsys::Encoding::CommandLineArguments args =
+    cmsys::Encoding::CommandLineArguments::Main(ac, av);
+  int argc = args.argc();
+  const char* const* argv = args.argv();
+
   std::string exename = argv[0];
   std::string logarg;
   bool nextarg = false;
diff --git a/Tests/CTestTestMemcheck/test.cmake.in b/Tests/CTestTestMemcheck/test.cmake.in
index 471e5a5..f2ffd06 100644
--- a/Tests/CTestTestMemcheck/test.cmake.in
+++ b/Tests/CTestTestMemcheck/test.cmake.in
@@ -9,12 +9,14 @@
 set(CTEST_BINARY_DIRECTORY              "@CMAKE_CURRENT_BINARY_DIR@/@SUBTEST_NAME@")
 set(CTEST_CVS_COMMAND                   "@CVSCOMMAND@")
 set(CTEST_CMAKE_GENERATOR               "@CMAKE_GENERATOR@")
+set(CTEST_CMAKE_GENERATOR_PLATFORM      "@CMAKE_GENERATOR_PLATFORM@")
 set(CTEST_CMAKE_GENERATOR_TOOLSET       "@CMAKE_GENERATOR_TOOLSET@")
 set(CTEST_BUILD_CONFIGURATION           "$ENV{CMAKE_CONFIG_TYPE}")
 set(CTEST_COVERAGE_COMMAND              "@COVERAGE_COMMAND@")
 set(CTEST_NOTES_FILES                   "${CTEST_SCRIPT_DIRECTORY}/${CTEST_SCRIPT_NAME}")
 
 set(CTEST_MEMORYCHECK_COMMAND "@CHECKER_COMMAND@")
+set(CTEST_MEMORYCHECK_TYPE "${MEMCHECK_TYPE}")
 
 @CTEST_EXTRA_CODE@
 
diff --git a/Tests/CTestTestMemcheck/testAddressSanitizer.cmake b/Tests/CTestTestMemcheck/testAddressSanitizer.cmake
new file mode 100644
index 0000000..3082e4b
--- /dev/null
+++ b/Tests/CTestTestMemcheck/testAddressSanitizer.cmake
@@ -0,0 +1,58 @@
+# this file simulates a program that has been built with address sanitizer
+# options
+
+message("ASAN_OPTIONS = [$ENV{ASAN_OPTIONS}]")
+string(REGEX REPLACE ".*log_path=\"([^\"]*)\".*" "\\1" LOG_FILE "$ENV{ASAN_OPTIONS}")
+message("LOG_FILE=[${LOG_FILE}]")
+
+# if we are not asked to simulate address sanitizer don't do it
+if(NOT "$ENV{ASAN_OPTIONS}]" MATCHES "simulate_sanitizer.1")
+  return()
+endif()
+# clear the log file
+file(REMOVE "${LOG_FILE}.2343")
+
+# create an example error from address santizer
+
+file(APPEND "${LOG_FILE}.2343"
+"=================================================================
+==19278== ERROR: AddressSanitizer: heap-buffer-overflow on address 0x60080000bffc at pc 0x4009f1 bp 0x7fff82de6520 sp 0x7fff82de6518
+WRITE of size 4 at 0x60080000bffc thread T0
+    #0 0x4009f0 (/home/kitware/msan/a.out+0x4009f0)
+    #1 0x7f18b02c876c (/lib/x86_64-linux-gnu/libc-2.15.so+0x2176c)
+    #2 0x400858 (/home/kitware/msan/a.out+0x400858)
+0x60080000bffc is located 4 bytes to the right of 40-byte region [0x60080000bfd0,0x60080000bff8)
+allocated by thread T0 here:
+    #0 0x7f18b088f9ca (/usr/lib/x86_64-linux-gnu/libasan.so.0.0.0+0x119ca)
+    #1 0x4009a2 (/home/kitware/msan/a.out+0x4009a2)
+    #2 0x7f18b02c876c (/lib/x86_64-linux-gnu/libc-2.15.so+0x2176c)
+Shadow bytes around the buggy address:
+  0x0c017fff97a0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
+  0x0c017fff97b0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
+  0x0c017fff97c0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
+  0x0c017fff97d0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
+  0x0c017fff97e0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
+=>0x0c017fff97f0: fa fa fa fa fa fa fa fa fa fa 00 00 00 00 00[fa]
+  0x0c017fff9800:fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
+  0x0c017fff9810: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
+  0x0c017fff9820: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
+  0x0c017fff9830: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
+  0x0c017fff9840: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
+Shadow byte legend (one shadow byte represents 8 application bytes):
+  Addressable:           00
+  Partially addressable: 01 02 03 04 05 06 07
+  Heap left redzone:     fa
+  Heap righ redzone:     fb
+  Freed Heap region:     fd
+  Stack left redzone:    f1
+  Stack mid redzone:     f2
+  Stack right redzone:   f3
+  Stack partial redzone: f4
+  Stack after return:    f5
+  Stack use after scope: f8
+  Global redzone:        f9
+  Global init order:     f6
+  Poisoned by user:      f7
+  ASan internal:         fe
+==19278== ABORTING
+")
diff --git a/Tests/CTestTestMemcheck/testLeakSanitizer.cmake b/Tests/CTestTestMemcheck/testLeakSanitizer.cmake
new file mode 100644
index 0000000..02030be
--- /dev/null
+++ b/Tests/CTestTestMemcheck/testLeakSanitizer.cmake
@@ -0,0 +1,47 @@
+# this file simulates a program that has been built with thread sanitizer
+# options
+
+message("ASAN_OPTIONS = [$ENV{ASAN_OPTIONS}]")
+string(REGEX REPLACE ".*log_path=\"([^\"]*)\".*" "\\1" LOG_FILE "$ENV{ASAN_OPTIONS}")
+message("LOG_FILE=[${LOG_FILE}]")
+# if we are not asked to simulate leak sanitizer don't do it
+if(NOT "$ENV{ASAN_OPTIONS}]" MATCHES "simulate_sanitizer.1")
+  return()
+endif()
+
+# clear the log file
+file(REMOVE "${LOG_FILE}.2343")
+file(REMOVE "${LOG_FILE}.2344")
+
+# create an error of each type of thread santizer
+# these names come from tsan_report.cc in llvm
+
+file(APPEND "${LOG_FILE}.2343"
+"=================================================================
+==25308==ERROR: LeakSanitizer: detected memory leaks
+
+Direct leak of 4360 byte(s) in 1 object(s) allocated from:
+    #0 0x46c669 in operator new[](unsigned long) (/home/kitware/msan/a.out+0x46c669)
+    #1 0x4823b4 in main /home/kitware/msan/memcheck.cxx:12
+    #2 0x7fa72bee476c in __libc_start_main /build/buildd/eglibc-2.15/csu/libc-start.c:226
+
+SUMMARY: AddressSanitizer: 4436 byte(s) leaked in 2 allocation(s).
+")
+file(APPEND "${LOG_FILE}.2342"
+"=================================================================
+==25308==ERROR: LeakSanitizer: detected memory leaks
+
+Direct leak of 76 byte(s) in 1 object(s) allocated from:
+    #0 0x46c669 in operator new[](unsigned long) (/home/kitware/msan/a.out+0x46c669)
+    #1 0x4821b8 in foo() /home/kitware/msan/memcheck.cxx:4
+    #2 0x4823f2 in main /home/kitware/msan/memcheck.cxx:14
+    #3 0x7fa72bee476c in __libc_start_main /build/buildd/eglibc-2.15/csu/libc-start.c:226
+
+Indirect leak of 76 byte(s) in 1 object(s) allocated from:
+    #0 0x46c669 in operator new[](unsigned long) (/home/kitware/msan/a.out+0x46c669)
+    #1 0x4821b8 in foo() /home/kitware/msan/memcheck.cxx:4
+    #2 0x4823f2 in main /home/kitware/msan/memcheck.cxx:14
+    #3 0x7fa72bee476c in __libc_start_main /build/buildd/eglibc-2.15/csu/libc-start.c:226
+
+SUMMARY: AddressSanitizer: 4436 byte(s) leaked in 2 allocation(s).
+")
diff --git a/Tests/CTestTestMemcheck/testMemorySanitizer.cmake b/Tests/CTestTestMemcheck/testMemorySanitizer.cmake
new file mode 100644
index 0000000..c87af9a
--- /dev/null
+++ b/Tests/CTestTestMemcheck/testMemorySanitizer.cmake
@@ -0,0 +1,27 @@
+# this file simulates a program that has been built with thread sanitizer
+# options
+
+message("MSAN_OPTIONS = [$ENV{MSAN_OPTIONS}]")
+string(REGEX REPLACE ".*log_path=\"([^\"]*)\".*" "\\1" LOG_FILE "$ENV{MSAN_OPTIONS}")
+message("LOG_FILE=[${LOG_FILE}]")
+
+# if we are not asked to simulate address sanitizer don't do it
+if(NOT "$ENV{MSAN_OPTIONS}]" MATCHES "simulate_sanitizer.1")
+  return()
+endif()
+# clear the log file
+file(REMOVE "${LOG_FILE}.2343")
+
+# create an error of each type of thread santizer
+# these names come from tsan_report.cc in llvm
+
+file(APPEND "${LOG_FILE}.2343"
+"=================================================================
+==28423== WARNING: MemorySanitizer: use-of-uninitialized-value
+    #0 0x7f4364210dd9 in main (/home/kitware/msan/msan-bin/umr+0x7bdd9)
+    #1 0x7f4362d9376c in __libc_start_main /build/buildd/eglibc-2.15/csu/libc-start.c:226
+    #2 0x7f4364210b0c in _start (/home/kitware/msan/msan-bin/umr+0x7bb0c)
+
+SUMMARY: MemorySanitizer: use-of-uninitialized-value ??:0 main
+Exiting
+")
diff --git a/Tests/CTestTestMemcheck/testThreadSanitizer.cmake b/Tests/CTestTestMemcheck/testThreadSanitizer.cmake
new file mode 100644
index 0000000..d591931
--- /dev/null
+++ b/Tests/CTestTestMemcheck/testThreadSanitizer.cmake
@@ -0,0 +1,47 @@
+# this file simulates a program that has been built with thread sanitizer
+# options
+
+message("TSAN_OPTIONS = [$ENV{TSAN_OPTIONS}]")
+string(REGEX REPLACE ".*log_path=\"([^\"]*)\".*" "\\1" LOG_FILE "$ENV{TSAN_OPTIONS}")
+message("LOG_FILE=[${LOG_FILE}]")
+
+set(error_types
+ "data race"
+ "data race on vptr (ctor/dtor vs virtual call)"
+ "heap-use-after-free"
+ "thread leak"
+ "destroy of a locked mutex"
+  "double lock of a mutex"
+  "unlock of an unlocked mutex (or by a wrong thread)"
+  "read lock of a write locked mutex"
+  "read unlock of a write locked mutex"
+  "signal-unsafe call inside of a signal"
+  "signal handler spoils errno"
+  "lock-order-inversion (potential deadlock)"
+ )
+
+# clear the log file
+file(REMOVE "${LOG_FILE}.2343")
+
+# create an error of each type of thread santizer
+# these names come from tsan_report.cc in llvm
+foreach(error_type ${error_types} )
+
+  file(APPEND "${LOG_FILE}.2343"
+"==================
+WARNING: ThreadSanitizer: ${error_type} (pid=27978)
+  Write of size 4 at 0x7fe017ce906c by thread T1:
+    #0 Thread1 ??:0 (exe+0x000000000bb0)
+    #1 <null> <null>:0 (libtsan.so.0+0x00000001b279)
+
+  Previous write of size 4 at 0x7fe017ce906c by main thread:
+    #0 main ??:0 (exe+0x000000000c3c)
+
+  Thread T1 (tid=27979, running) created by main thread at:
+    #0 <null> <null>:0 (libtsan.so.0+0x00000001ed7b)
+    #1 main ??:0 (exe+0x000000000c2c)
+
+SUMMARY: ThreadSanitizer: ${error_type} ??:0 Thread1
+==================
+")
+endforeach()
diff --git a/Tests/CTestTestMemcheck/testUndefinedBehaviorSanitizer.cmake b/Tests/CTestTestMemcheck/testUndefinedBehaviorSanitizer.cmake
new file mode 100644
index 0000000..8ef3c0a
--- /dev/null
+++ b/Tests/CTestTestMemcheck/testUndefinedBehaviorSanitizer.cmake
@@ -0,0 +1,21 @@
+# this file simulates a program that has been built with undefined behavior
+# sanitizer options
+
+message("UBSAN_OPTIONS = [$ENV{UBSAN_OPTIONS}]")
+string(REGEX REPLACE ".*log_path=\"([^\"]*)\".*" "\\1" LOG_FILE "$ENV{UBSAN_OPTIONS}")
+message("LOG_FILE=[${LOG_FILE}]")
+
+# if we are not asked to simulate address sanitizer don't do it
+if(NOT "$ENV{UBSAN_OPTIONS}]" MATCHES "simulate_sanitizer.1")
+  return()
+endif()
+# clear the log file
+file(REMOVE "${LOG_FILE}.2343")
+
+# create an error like undefined behavior santizer creates;
+# these names come from ubsan_diag.cc and ubsan_handlers.cc
+# in llvm
+
+file(APPEND "${LOG_FILE}.2343"
+"<unknown>: runtime error: left shift of negative value -256
+")
diff --git a/Tests/CTestTestParallel/CTestConfig.cmake b/Tests/CTestTestParallel/CTestConfig.cmake
index c3c5038..fc5b666 100644
--- a/Tests/CTestTestParallel/CTestConfig.cmake
+++ b/Tests/CTestTestParallel/CTestConfig.cmake
@@ -2,6 +2,6 @@
 set(CTEST_NIGHTLY_START_TIME "21:00:00 EDT")
 set(CTEST_DART_SERVER_VERSION "2")
 set(CTEST_DROP_METHOD "http")
-set(CTEST_DROP_SITE "www.cdash.org")
-set(CTEST_DROP_LOCATION "/CDash/submit.php?project=PublicDashboard")
+set(CTEST_DROP_SITE "open.cdash.org")
+set(CTEST_DROP_LOCATION "/submit.php?project=PublicDashboard")
 set(CTEST_DROP_SITE_CDASH TRUE)
diff --git a/Tests/CTestTestParallel/test.cmake.in b/Tests/CTestTestParallel/test.cmake.in
index 48631ca..045a4ca 100644
--- a/Tests/CTestTestParallel/test.cmake.in
+++ b/Tests/CTestTestParallel/test.cmake.in
@@ -9,6 +9,7 @@
 set(CTEST_BINARY_DIRECTORY              "@CMake_BINARY_DIR@/Tests/CTestTestParallel")
 set(CTEST_CVS_COMMAND                   "@CVSCOMMAND@")
 set(CTEST_CMAKE_GENERATOR               "@CMAKE_GENERATOR@")
+set(CTEST_CMAKE_GENERATOR_PLATFORM      "@CMAKE_GENERATOR_PLATFORM@")
 set(CTEST_CMAKE_GENERATOR_TOOLSET       "@CMAKE_GENERATOR_TOOLSET@")
 set(CTEST_BUILD_CONFIGURATION           "$ENV{CMAKE_CONFIG_TYPE}")
 set(CTEST_COVERAGE_COMMAND              "@COVERAGE_COMMAND@")
diff --git a/Tests/CTestTestResourceLock/CTestConfig.cmake b/Tests/CTestTestResourceLock/CTestConfig.cmake
index 5fb560b..c118777 100644
--- a/Tests/CTestTestResourceLock/CTestConfig.cmake
+++ b/Tests/CTestTestResourceLock/CTestConfig.cmake
@@ -2,6 +2,6 @@
 set(CTEST_NIGHTLY_START_TIME "21:00:00 EDT")
 set(CTEST_DART_SERVER_VERSION "2")
 set(CTEST_DROP_METHOD "http")
-set(CTEST_DROP_SITE "www.cdash.org")
-set(CTEST_DROP_LOCATION "/CDash/submit.php?project=PublicDashboard")
+set(CTEST_DROP_SITE "open.cdash.org")
+set(CTEST_DROP_LOCATION "/submit.php?project=PublicDashboard")
 set(CTEST_DROP_SITE_CDASH TRUE)
diff --git a/Tests/CTestTestResourceLock/test.cmake.in b/Tests/CTestTestResourceLock/test.cmake.in
index 6ec6dfe..67dde18 100644
--- a/Tests/CTestTestResourceLock/test.cmake.in
+++ b/Tests/CTestTestResourceLock/test.cmake.in
@@ -9,6 +9,7 @@
 set(CTEST_BINARY_DIRECTORY              "@CMake_BINARY_DIR@/Tests/CTestTestResourceLock")
 set(CTEST_CVS_COMMAND                   "@CVSCOMMAND@")
 set(CTEST_CMAKE_GENERATOR               "@CMAKE_GENERATOR@")
+set(CTEST_CMAKE_GENERATOR_PLATFORM      "@CMAKE_GENERATOR_PLATFORM@")
 set(CTEST_CMAKE_GENERATOR_TOOLSET       "@CMAKE_GENERATOR_TOOLSET@")
 set(CTEST_BUILD_CONFIGURATION           "$ENV{CMAKE_CONFIG_TYPE}")
 set(CTEST_COVERAGE_COMMAND              "@COVERAGE_COMMAND@")
diff --git a/Tests/CTestTestScheduler/CTestConfig.cmake b/Tests/CTestTestScheduler/CTestConfig.cmake
index 7da8f6f..797387b 100644
--- a/Tests/CTestTestScheduler/CTestConfig.cmake
+++ b/Tests/CTestTestScheduler/CTestConfig.cmake
@@ -2,6 +2,6 @@
 set(CTEST_NIGHTLY_START_TIME "21:00:00 EDT")
 set(CTEST_DART_SERVER_VERSION "2")
 set(CTEST_DROP_METHOD "http")
-set(CTEST_DROP_SITE "www.cdash.org")
-set(CTEST_DROP_LOCATION "/CDash/submit.php?project=PublicDashboard")
+set(CTEST_DROP_SITE "open.cdash.org")
+set(CTEST_DROP_LOCATION "/submit.php?project=PublicDashboard")
 set(CTEST_DROP_SITE_CDASH TRUE)
diff --git a/Tests/CTestTestScheduler/test.cmake.in b/Tests/CTestTestScheduler/test.cmake.in
index 06ba33e..f8c8ab7 100644
--- a/Tests/CTestTestScheduler/test.cmake.in
+++ b/Tests/CTestTestScheduler/test.cmake.in
@@ -9,6 +9,7 @@
 set(CTEST_BINARY_DIRECTORY              "@CMake_BINARY_DIR@/Tests/CTestTestScheduler")
 set(CTEST_CVS_COMMAND                   "@CVSCOMMAND@")
 set(CTEST_CMAKE_GENERATOR               "@CMAKE_GENERATOR@")
+set(CTEST_CMAKE_GENERATOR_PLATFORM      "@CMAKE_GENERATOR_PLATFORM@")
 set(CTEST_CMAKE_GENERATOR_TOOLSET       "@CMAKE_GENERATOR_TOOLSET@")
 set(CTEST_BUILD_CONFIGURATION           "$ENV{CMAKE_CONFIG_TYPE}")
 set(CTEST_COVERAGE_COMMAND              "@COVERAGE_COMMAND@")
diff --git a/Tests/CTestTestSkipReturnCode/CTestConfig.cmake b/Tests/CTestTestSkipReturnCode/CTestConfig.cmake
index ad8e00e..da0c76b 100644
--- a/Tests/CTestTestSkipReturnCode/CTestConfig.cmake
+++ b/Tests/CTestTestSkipReturnCode/CTestConfig.cmake
@@ -2,6 +2,6 @@
 set (CTEST_NIGHTLY_START_TIME "21:00:00 EDT")
 set (CTEST_DART_SERVER_VERSION "2")
 set(CTEST_DROP_METHOD "http")
-set(CTEST_DROP_SITE "www.cdash.org")
-set(CTEST_DROP_LOCATION "/CDash/submit.php?project=PublicDashboard")
+set(CTEST_DROP_SITE "open.cdash.org")
+set(CTEST_DROP_LOCATION "/submit.php?project=PublicDashboard")
 set(CTEST_DROP_SITE_CDASH TRUE)
diff --git a/Tests/CTestTestSkipReturnCode/test.cmake.in b/Tests/CTestTestSkipReturnCode/test.cmake.in
index d3c44f5..112b0cd 100644
--- a/Tests/CTestTestSkipReturnCode/test.cmake.in
+++ b/Tests/CTestTestSkipReturnCode/test.cmake.in
@@ -9,6 +9,7 @@
 set(CTEST_BINARY_DIRECTORY              "@CMake_BINARY_DIR@/Tests/CTestTestSkipReturnCode")
 set(CTEST_CVS_COMMAND                   "@CVSCOMMAND@")
 set(CTEST_CMAKE_GENERATOR               "@CMAKE_GENERATOR@")
+set(CTEST_CMAKE_GENERATOR_PLATFORM      "@CMAKE_GENERATOR_PLATFORM@")
 set(CTEST_CMAKE_GENERATOR_TOOLSET       "@CMAKE_GENERATOR_TOOLSET@")
 set(CTEST_BUILD_CONFIGURATION           "$ENV{CMAKE_CONFIG_TYPE}")
 set(CTEST_COVERAGE_COMMAND              "@COVERAGE_COMMAND@")
diff --git a/Tests/CTestTestStopTime/CTestConfig.cmake b/Tests/CTestTestStopTime/CTestConfig.cmake
index 129db4d..412283e 100644
--- a/Tests/CTestTestStopTime/CTestConfig.cmake
+++ b/Tests/CTestTestStopTime/CTestConfig.cmake
@@ -2,6 +2,6 @@
 set (CTEST_NIGHTLY_START_TIME "21:00:00 EDT")
 set (CTEST_DART_SERVER_VERSION "2")
 set(CTEST_DROP_METHOD "http")
-set(CTEST_DROP_SITE "www.cdash.org")
-set(CTEST_DROP_LOCATION "/CDash/submit.php?project=PublicDashboard")
+set(CTEST_DROP_SITE "open.cdash.org")
+set(CTEST_DROP_LOCATION "/submit.php?project=PublicDashboard")
 set(CTEST_DROP_SITE_CDASH TRUE)
diff --git a/Tests/CTestTestStopTime/test.cmake.in b/Tests/CTestTestStopTime/test.cmake.in
index 8adf941..d3a9a4a 100644
--- a/Tests/CTestTestStopTime/test.cmake.in
+++ b/Tests/CTestTestStopTime/test.cmake.in
@@ -9,6 +9,7 @@
 set(CTEST_BINARY_DIRECTORY              "@CMake_BINARY_DIR@/Tests/CTestTestStopTime")
 set(CTEST_CVS_COMMAND                   "@CVSCOMMAND@")
 set(CTEST_CMAKE_GENERATOR               "@CMAKE_GENERATOR@")
+set(CTEST_CMAKE_GENERATOR_PLATFORM      "@CMAKE_GENERATOR_PLATFORM@")
 set(CTEST_CMAKE_GENERATOR_TOOLSET       "@CMAKE_GENERATOR_TOOLSET@")
 set(CTEST_BUILD_CONFIGURATION           "$ENV{CMAKE_CONFIG_TYPE}")
 set(CTEST_COVERAGE_COMMAND              "@COVERAGE_COMMAND@")
diff --git a/Tests/CTestTestSubdir/CTestConfig.cmake b/Tests/CTestTestSubdir/CTestConfig.cmake
index 4b848aa..47ebb92 100644
--- a/Tests/CTestTestSubdir/CTestConfig.cmake
+++ b/Tests/CTestTestSubdir/CTestConfig.cmake
@@ -2,6 +2,6 @@
 set(CTEST_NIGHTLY_START_TIME "21:00:00 EDT")
 set(CTEST_DART_SERVER_VERSION "2")
 set(CTEST_DROP_METHOD "http")
-set(CTEST_DROP_SITE "www.cdash.org")
-set(CTEST_DROP_LOCATION "/CDash/submit.php?project=PublicDashboard")
+set(CTEST_DROP_SITE "open.cdash.org")
+set(CTEST_DROP_LOCATION "/submit.php?project=PublicDashboard")
 set(CTEST_DROP_SITE_CDASH TRUE)
diff --git a/Tests/CTestTestSubdir/test.cmake.in b/Tests/CTestTestSubdir/test.cmake.in
index 5a6caf1..8b3957b 100644
--- a/Tests/CTestTestSubdir/test.cmake.in
+++ b/Tests/CTestTestSubdir/test.cmake.in
@@ -9,6 +9,7 @@
 set(CTEST_BINARY_DIRECTORY              "@CMake_BINARY_DIR@/Tests/CTestTestSubdir")
 set(CTEST_CVS_COMMAND                   "@CVSCOMMAND@")
 set(CTEST_CMAKE_GENERATOR               "@CMAKE_GENERATOR@")
+set(CTEST_CMAKE_GENERATOR_PLATFORM      "@CMAKE_GENERATOR_PLATFORM@")
 set(CTEST_CMAKE_GENERATOR_TOOLSET       "@CMAKE_GENERATOR_TOOLSET@")
 set(CTEST_BUILD_CONFIGURATION           "$ENV{CMAKE_CONFIG_TYPE}")
 set(CTEST_COVERAGE_COMMAND              "@COVERAGE_COMMAND@")
diff --git a/Tests/CTestTestTimeout/CMakeLists.txt b/Tests/CTestTestTimeout/CMakeLists.txt
index 2e3bd6a..c6cbc47 100644
--- a/Tests/CTestTestTimeout/CMakeLists.txt
+++ b/Tests/CTestTestTimeout/CMakeLists.txt
@@ -3,11 +3,8 @@
 include(CTest)
 
 if(NOT TIMEOUT)
-  if(CYGWIN)
-    set(TIMEOUT 4) # Cygwin CMake sometimes takes > 1 second to load!
-  else()
-    set(TIMEOUT 1)
-  endif()
+  # Give the process time to load and start running.
+  set(TIMEOUT 4)
 endif()
 
 add_definitions(-DTIMEOUT=${TIMEOUT})
diff --git a/Tests/CTestTestTimeout/CTestConfig.cmake b/Tests/CTestTestTimeout/CTestConfig.cmake
index 76d62ad..13114f1 100644
--- a/Tests/CTestTestTimeout/CTestConfig.cmake
+++ b/Tests/CTestTestTimeout/CTestConfig.cmake
@@ -2,6 +2,6 @@
 set(CTEST_NIGHTLY_START_TIME "21:00:00 EDT")
 set(CTEST_DART_SERVER_VERSION "2")
 set(CTEST_DROP_METHOD "http")
-set(CTEST_DROP_SITE "www.cdash.org")
-set(CTEST_DROP_LOCATION "/CDash/submit.php?project=PublicDashboard")
+set(CTEST_DROP_SITE "open.cdash.org")
+set(CTEST_DROP_LOCATION "/submit.php?project=PublicDashboard")
 set(CTEST_DROP_SITE_CDASH TRUE)
diff --git a/Tests/CTestTestTimeout/test.cmake.in b/Tests/CTestTestTimeout/test.cmake.in
index 68c74d8..4b5157e 100644
--- a/Tests/CTestTestTimeout/test.cmake.in
+++ b/Tests/CTestTestTimeout/test.cmake.in
@@ -9,6 +9,7 @@
 set(CTEST_BINARY_DIRECTORY              "@CMake_BINARY_DIR@/Tests/CTestTestTimeout")
 set(CTEST_CVS_COMMAND                   "@CVSCOMMAND@")
 set(CTEST_CMAKE_GENERATOR               "@CMAKE_GENERATOR@")
+set(CTEST_CMAKE_GENERATOR_PLATFORM      "@CMAKE_GENERATOR_PLATFORM@")
 set(CTEST_CMAKE_GENERATOR_TOOLSET       "@CMAKE_GENERATOR_TOOLSET@")
 set(CTEST_BUILD_CONFIGURATION           "$ENV{CMAKE_CONFIG_TYPE}")
 set(CTEST_COVERAGE_COMMAND              "@COVERAGE_COMMAND@")
@@ -32,7 +33,7 @@
   if(after_sleep)
     message(FATAL_ERROR "Log indicates timeout did not kill child.")
   else()
-    message("Log indicates timeout correctly killed child.")
+    message(STATUS "Log indicates timeout correctly killed child.")
   endif()
 else()
   message(FATAL_ERROR "Log does not exist:\n  ${log}")
diff --git a/Tests/CTestTestUpload/CTestConfig.cmake b/Tests/CTestTestUpload/CTestConfig.cmake
index 89c5b94..a547088 100644
--- a/Tests/CTestTestUpload/CTestConfig.cmake
+++ b/Tests/CTestTestUpload/CTestConfig.cmake
@@ -2,6 +2,6 @@
 set (CTEST_NIGHTLY_START_TIME "21:00:00 EDT")
 set (CTEST_DART_SERVER_VERSION "2")
 set (CTEST_DROP_METHOD "http")
-set (CTEST_DROP_SITE "www.cdash.org")
-set (CTEST_DROP_LOCATION "/CDash/submit.php?project=PublicDashboard")
+set (CTEST_DROP_SITE "open.cdash.org")
+set (CTEST_DROP_LOCATION "/submit.php?project=PublicDashboard")
 set (CTEST_DROP_SITE_CDASH TRUE)
diff --git a/Tests/CTestTestUpload/test.cmake.in b/Tests/CTestTestUpload/test.cmake.in
index bb6ba25..701439d 100644
--- a/Tests/CTestTestUpload/test.cmake.in
+++ b/Tests/CTestTestUpload/test.cmake.in
@@ -8,6 +8,7 @@
 set(CTEST_SOURCE_DIRECTORY              "@CMake_SOURCE_DIR@/Tests/CTestTestUpload")
 set(CTEST_BINARY_DIRECTORY              "@CMake_BINARY_DIR@/Tests/CTestTestUpload")
 set(CTEST_CMAKE_GENERATOR               "@CMAKE_GENERATOR@")
+set(CTEST_CMAKE_GENERATOR_PLATFORM      "@CMAKE_GENERATOR_PLATFORM@")
 set(CTEST_CMAKE_GENERATOR_TOOLSET       "@CMAKE_GENERATOR_TOOLSET@")
 set(CTEST_BUILD_CONFIGURATION           "$ENV{CMAKE_CONFIG_TYPE}")
 
diff --git a/Tests/CTestTestZeroTimeout/CTestConfig.cmake b/Tests/CTestTestZeroTimeout/CTestConfig.cmake
index f8e0609..6094864 100644
--- a/Tests/CTestTestZeroTimeout/CTestConfig.cmake
+++ b/Tests/CTestTestZeroTimeout/CTestConfig.cmake
@@ -2,6 +2,6 @@
 set(CTEST_NIGHTLY_START_TIME "21:00:00 EDT")
 set(CTEST_DART_SERVER_VERSION "2")
 set(CTEST_DROP_METHOD "http")
-set(CTEST_DROP_SITE "www.cdash.org")
-set(CTEST_DROP_LOCATION "/CDash/submit.php?project=PublicDashboard")
+set(CTEST_DROP_SITE "open.cdash.org")
+set(CTEST_DROP_LOCATION "/submit.php?project=PublicDashboard")
 set(CTEST_DROP_SITE_CDASH TRUE)
diff --git a/Tests/CTestTestZeroTimeout/test.cmake.in b/Tests/CTestTestZeroTimeout/test.cmake.in
index beb6d90..b829fef 100644
--- a/Tests/CTestTestZeroTimeout/test.cmake.in
+++ b/Tests/CTestTestZeroTimeout/test.cmake.in
@@ -9,6 +9,7 @@
 set(CTEST_BINARY_DIRECTORY              "@CMake_BINARY_DIR@/Tests/CTestTestZeroTimeout")
 set(CTEST_CVS_COMMAND                   "@CVSCOMMAND@")
 set(CTEST_CMAKE_GENERATOR               "@CMAKE_GENERATOR@")
+set(CTEST_CMAKE_GENERATOR_PLATFORM      "@CMAKE_GENERATOR_PLATFORM@")
 set(CTEST_CMAKE_GENERATOR_TOOLSET       "@CMAKE_GENERATOR_TOOLSET@")
 set(CTEST_BUILD_CONFIGURATION           "$ENV{CMAKE_CONFIG_TYPE}")
 set(CTEST_COVERAGE_COMMAND              "@COVERAGE_COMMAND@")
diff --git a/Tests/CTestUpdateCommon.cmake b/Tests/CTestUpdateCommon.cmake
index 857c6f5..97153f0 100644
--- a/Tests/CTestUpdateCommon.cmake
+++ b/Tests/CTestUpdateCommon.cmake
@@ -219,6 +219,36 @@
 endfunction()
 
 #-----------------------------------------------------------------------------
+# Function to find the Update.xml file and make sure
+# it only has the Revision in it and no updates
+function(check_no_update bin_dir)
+  set(PATTERN ${TOP}/${bin_dir}/Testing/*/Update.xml)
+  file(GLOB UPDATE_XML_FILE RELATIVE ${TOP} ${PATTERN})
+  string(REGEX REPLACE "//Update.xml$" "/Update.xml"
+    UPDATE_XML_FILE "${UPDATE_XML_FILE}")
+  message(" found ${UPDATE_XML_FILE}")
+  set(rev_regex "Revision|PriorRevision")
+  file(STRINGS ${TOP}/${UPDATE_XML_FILE} UPDATE_XML_REVISIONS
+    REGEX "^\t<(${rev_regex})>[^<\n]+</(${rev_regex})>$"
+    )
+  set(found_revisons FALSE)
+  foreach(r IN LISTS UPDATE_XML_REVISIONS)
+    if("${r}" MATCHES "PriorRevision")
+      message(FATAL_ERROR "Found PriorRevision in no update test")
+    endif()
+    if("${r}" MATCHES "<Revision>")
+      set(found_revisons TRUE)
+    endif()
+  endforeach()
+  if(found_revisons)
+    message(" found <Revision> in no update test")
+  else()
+    message(FATAL_ERROR " missing <Revision> in no update test")
+  endif()
+endfunction()
+
+
+#-----------------------------------------------------------------------------
 # Function to run the dashboard through a script
 function(run_dashboard_script bin_dir)
   run_child(
@@ -228,13 +258,17 @@
 
   # Verify the updates reported by CTest.
   list(APPEND UPDATE_MAYBE Updated{subdir} Updated{CTestConfig.cmake})
-  check_updates(${bin_dir}
-    Updated{foo.txt}
-    Updated{bar.txt}
-    Updated{zot.txt}
-    Updated{subdir/foo.txt}
-    Updated{subdir/bar.txt}
-    )
+  if(NO_UPDATE)
+    check_no_update(${bin_dir})
+  else()
+    check_updates(${bin_dir}
+      Updated{foo.txt}
+      Updated{bar.txt}
+      Updated{zot.txt}
+      Updated{subdir/foo.txt}
+      Updated{subdir/bar.txt}
+      )
+  endif()
 endfunction()
 
 #-----------------------------------------------------------------------------
diff --git a/Tests/CTestUpdateGIT.cmake.in b/Tests/CTestUpdateGIT.cmake.in
index f6939de..41b732b 100644
--- a/Tests/CTestUpdateGIT.cmake.in
+++ b/Tests/CTestUpdateGIT.cmake.in
@@ -317,3 +317,20 @@
 
 # Run the dashboard script with CTest.
 run_dashboard_script(dash-binary-custom)
+
+
+rewind_source(dash-source)
+
+#-----------------------------------------------------------------------------
+# Test no update with a dashboard script.
+message("Running CTest Dashboard Script (No update)...")
+
+create_dashboard_script(dash-binary-no-update
+  "# git command configuration
+set(CTEST_GIT_COMMAND \"${GIT}\")
+set(CTEST_UPDATE_VERSION_ONLY TRUE)
+")
+
+# Run the dashboard script with CTest.
+set(NO_UPDATE 1)
+run_dashboard_script(dash-binary-no-update)
diff --git a/Tests/CheckCompilerRelatedVariables/CMakeLists.txt b/Tests/CheckCompilerRelatedVariables/CMakeLists.txt
index 69cfdb8..87b7f1a 100644
--- a/Tests/CheckCompilerRelatedVariables/CMakeLists.txt
+++ b/Tests/CheckCompilerRelatedVariables/CMakeLists.txt
@@ -40,6 +40,9 @@
 if(DEFINED MSVC12)
   math(EXPR msvc_total "${msvc_total} + 1")
 endif()
+if(DEFINED MSVC14)
+  math(EXPR msvc_total "${msvc_total} + 1")
+endif()
 
 echo_var(MSVC)
 echo_var(MSVC60)
@@ -50,6 +53,7 @@
 echo_var(MSVC10)
 echo_var(MSVC11)
 echo_var(MSVC12)
+echo_var(MSVC14)
 echo_var(MSVC_IDE)
 
 if(MSVC)
diff --git a/Tests/CompatibleInterface/CMakeLists.txt b/Tests/CompatibleInterface/CMakeLists.txt
index 350b518..668a97b 100644
--- a/Tests/CompatibleInterface/CMakeLists.txt
+++ b/Tests/CompatibleInterface/CMakeLists.txt
@@ -1,5 +1,5 @@
 
-cmake_minimum_required(VERSION 2.8)
+cmake_minimum_required(VERSION 3.0)
 
 project(CompatibleInterface)
 
@@ -54,6 +54,15 @@
 add_executable(CompatibleInterface main.cpp)
 target_link_libraries(CompatibleInterface iface1)
 
+add_library(foo STATIC foo.cpp)
+add_library(bar SHARED bar.cpp)
+set_property(TARGET foo APPEND PROPERTY COMPATIBLE_INTERFACE_BOOL SOMEPROP)
+set_property(TARGET foo PROPERTY INTERFACE_SOMEPROP ON)
+# Use LINK_ONLY to suppress usage requirements and allow the check to pass.
+set_property(TARGET bar PROPERTY INTERFACE_LINK_LIBRARIES $<LINK_ONLY:foo>)
+set_property(TARGET CompatibleInterface PROPERTY SOMEPROP OFF)
+target_link_libraries(CompatibleInterface bar)
+
 set_property(TARGET CompatibleInterface PROPERTY BOOL_PROP2 ON)
 set_property(TARGET CompatibleInterface PROPERTY BOOL_PROP3 ON)
 set_property(TARGET CompatibleInterface PROPERTY STRING_PROP2 prop2)
diff --git a/Tests/CompatibleInterface/bar.cpp b/Tests/CompatibleInterface/bar.cpp
new file mode 100644
index 0000000..2e09900
--- /dev/null
+++ b/Tests/CompatibleInterface/bar.cpp
@@ -0,0 +1,7 @@
+#ifdef _WIN32
+__declspec(dllexport)
+#endif
+int bar()
+{
+  return 0;
+}
diff --git a/Tests/CompatibleInterface/foo.cpp b/Tests/CompatibleInterface/foo.cpp
new file mode 100644
index 0000000..e05eb7e
--- /dev/null
+++ b/Tests/CompatibleInterface/foo.cpp
@@ -0,0 +1,4 @@
+int foo()
+{
+  return 0;
+}
diff --git a/Tests/CompatibleInterface/main.cpp b/Tests/CompatibleInterface/main.cpp
index e23625a..d20b64b 100644
--- a/Tests/CompatibleInterface/main.cpp
+++ b/Tests/CompatibleInterface/main.cpp
@@ -40,8 +40,14 @@
 
 #include "iface2.h"
 
+int foo();
+#ifdef _WIN32
+__declspec(dllimport)
+#endif
+int bar();
+
 int main(int argc, char **argv)
 {
   Iface2 if2;
-  return if2.foo();
+  return if2.foo() + foo() + bar();
 }
diff --git a/Tests/CompileDefinitions/target_prop/CMakeLists.txt b/Tests/CompileDefinitions/target_prop/CMakeLists.txt
index 2ca2869..311975c 100644
--- a/Tests/CompileDefinitions/target_prop/CMakeLists.txt
+++ b/Tests/CompileDefinitions/target_prop/CMakeLists.txt
@@ -53,3 +53,8 @@
     "LINK_LANGUAGE_IS_$<TARGET_PROPERTY:LINKER_LANGUAGE>"
     "C_EXECUTABLE_LINK_LANGUAGE_IS_$<TARGET_PROPERTY:target_prop_c_executable,LINKER_LANGUAGE>"
     )
+
+add_library(tgt STATIC IMPORTED)
+set_property(TARGET tgt APPEND PROPERTY COMPILE_DEFINITIONS TGT_DEF TGT_TYPE_$<TARGET_PROPERTY:TYPE>)
+add_executable(usetgt usetgt.c)
+target_compile_definitions(usetgt PRIVATE $<TARGET_PROPERTY:tgt,COMPILE_DEFINITIONS>)
diff --git a/Tests/CompileDefinitions/target_prop/usetgt.c b/Tests/CompileDefinitions/target_prop/usetgt.c
new file mode 100644
index 0000000..6672a3e
--- /dev/null
+++ b/Tests/CompileDefinitions/target_prop/usetgt.c
@@ -0,0 +1,10 @@
+#ifndef TGT_DEF
+# error TGT_DEF incorrectly not defined
+#endif
+#ifndef TGT_TYPE_STATIC_LIBRARY
+# error TGT_TYPE_STATIC_LIBRARY incorrectly not defined
+#endif
+#ifdef TGT_TYPE_EXECUTABLE
+# error TGT_TYPE_EXECUTABLE incorrectly defined
+#endif
+int main(void) { return 0; }
diff --git a/Tests/CompileOptions/CMakeLists.txt b/Tests/CompileOptions/CMakeLists.txt
index 9b6c9c2..05a5f82 100644
--- a/Tests/CompileOptions/CMakeLists.txt
+++ b/Tests/CompileOptions/CMakeLists.txt
@@ -22,6 +22,12 @@
   ${cxx_tests}
   )
 
+if(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang|Borland")
+  set_property(TARGET CompileOptions APPEND PROPERTY COMPILE_OPTIONS
+    "-DTEST_OCTOTHORPE=\"#\""
+    )
+endif()
+
 target_link_libraries(CompileOptions testlib)
 
 if(CMAKE_CXX_COMPILER_ID MATCHES "GNU")
diff --git a/Tests/CompileOptions/main.cpp b/Tests/CompileOptions/main.cpp
index 42f4cca..f3c1355 100644
--- a/Tests/CompileOptions/main.cpp
+++ b/Tests/CompileOptions/main.cpp
@@ -17,6 +17,9 @@
 int main()
 {
   return (strcmp(NEEDS_ESCAPE, "E$CAPE") == 0
+#ifdef TEST_OCTOTHORPE
+      && strcmp(TEST_OCTOTHORPE, "#") == 0
+#endif
       && strcmp(EXPECTED_C_COMPILER_VERSION, TEST_C_COMPILER_VERSION) == 0
       && strcmp(EXPECTED_CXX_COMPILER_VERSION, TEST_CXX_COMPILER_VERSION) == 0
       && TEST_C_COMPILER_VERSION_EQUALITY == 1
diff --git a/Tests/Complex/CMakeLists.txt b/Tests/Complex/CMakeLists.txt
index 222250c..5e5eead 100644
--- a/Tests/Complex/CMakeLists.txt
+++ b/Tests/Complex/CMakeLists.txt
@@ -14,6 +14,21 @@
   endif()
 endif()
 
+# It is not recommended to set a policy to OLD, but this test
+# covers the OLD behavior of some policies.
+foreach(p
+    CMP0029
+    CMP0032
+    CMP0033
+    CMP0034
+    CMP0043
+    CMP0050
+    )
+  if(POLICY ${p})
+    cmake_policy(SET ${p} OLD)
+  endif()
+endforeach()
+
 # Test building without per-rule echo lines in Makefiles.
 set_property(GLOBAL PROPERTY RULE_MESSAGES OFF)
 
diff --git a/Tests/ComplexOneConfig/CMakeLists.txt b/Tests/ComplexOneConfig/CMakeLists.txt
index 3f17dcc..3b73e70 100644
--- a/Tests/ComplexOneConfig/CMakeLists.txt
+++ b/Tests/ComplexOneConfig/CMakeLists.txt
@@ -14,6 +14,21 @@
   endif()
 endif()
 
+# It is not recommended to set a policy to OLD, but this test
+# covers the OLD behavior of some policies.
+foreach(p
+    CMP0029
+    CMP0032
+    CMP0033
+    CMP0034
+    CMP0043
+    CMP0050
+    )
+  if(POLICY ${p})
+    cmake_policy(SET ${p} OLD)
+  endif()
+endforeach()
+
 # Test building without per-rule echo lines in Makefiles.
 set_property(GLOBAL PROPERTY RULE_MESSAGES OFF)
 
diff --git a/Tests/ExportImport/CMakeLists.txt b/Tests/ExportImport/CMakeLists.txt
index a6f8921..eaad3d4 100644
--- a/Tests/ExportImport/CMakeLists.txt
+++ b/Tests/ExportImport/CMakeLists.txt
@@ -44,6 +44,7 @@
     --build-project Export
     --build-target install
     --build-generator ${CMAKE_GENERATOR}
+    --build-generator-platform "${CMAKE_GENERATOR_PLATFORM}"
     --build-generator-toolset "${CMAKE_GENERATOR_TOOLSET}"
     --build-options -C${ExportImport_BINARY_DIR}/InitialCache.cmake
   VERBATIM
@@ -65,6 +66,7 @@
    --build-noclean
    --build-project Import
    --build-generator ${CMAKE_GENERATOR}
+   --build-generator-platform "${CMAKE_GENERATOR_PLATFORM}"
    --build-generator-toolset "${CMAKE_GENERATOR_TOOLSET}"
    --build-options -C${ExportImport_BINARY_DIR}/InitialCache.cmake
   VERBATIM
diff --git a/Tests/ExternalProject/CMakeLists.txt b/Tests/ExternalProject/CMakeLists.txt
index 0ed5561..d2fa86a 100644
--- a/Tests/ExternalProject/CMakeLists.txt
+++ b/Tests/ExternalProject/CMakeLists.txt
@@ -3,6 +3,8 @@
 
 include(ExternalProject)
 
+# Test ExternalProject, especially with checkouts from VCS
+
 find_package(CVS)
 find_package(Subversion)
 find_package(Git)
@@ -23,33 +25,6 @@
 set_property(DIRECTORY PROPERTY EP_BASE ${base})
 set_property(DIRECTORY PROPERTY EP_STEP_TARGETS configure build test)
 
-if(NOT DEFINED can_build_tutorial_step5)
-  set(can_build_tutorial_step5 1)
-
-  # Tutorial Step5 cannot build correctly using Visual Studio 6
-  # on Windows 98 if the path of its build tree exceeds 72
-  # characters in length... So don't attempt to build it
-  # in a long path on Win98:
-  #
-  if(CMAKE_SYSTEM STREQUAL "Windows-4.10")
-    string(LENGTH "${binary_base}/TutorialStep5-Local" n)
-    if(n GREATER 72)
-      set(can_build_tutorial_step5 0)
-    endif()
-  endif()
-
-  # The ExternalProject builds of Tutorial Step5 cannot be built
-  # correctly 2nd and later times in an in-source build...
-  # (because the CMakeCache.txt from the real in-source build of
-  # the Tests/Tutorial/Step5 directory gets copied when we do
-  # the "source directory copy" step... but it still refers to
-  # its original path which yields a configure error.) So:
-  #
-  if("${CMAKE_SOURCE_DIR}" STREQUAL "${CMAKE_BINARY_DIR}")
-    set(can_build_tutorial_step5 0)
-  endif()
-endif()
-
 add_custom_target(NonExternalProjectTarget
   COMMAND ${CMAKE_COMMAND} -E echo NonExternalProjectTarget)
 
@@ -116,142 +91,6 @@
 set_property(TARGET ${proj} PROPERTY FOLDER "")
 
 
-# Local DIR:
-#
-if(can_build_tutorial_step5)
-  set(proj TutorialStep5-Local)
-  ExternalProject_Add(${proj}
-    URL "${CMAKE_CURRENT_SOURCE_DIR}/../Tutorial/Step5"
-    CMAKE_CACHE_ARGS -DCMAKE_INSTALL_PREFIX:PATH=<INSTALL_DIR>
-    CMAKE_ARGS -G ${CMAKE_GENERATOR} <SOURCE_DIR>
-    TEST_BEFORE_INSTALL 1
-    LOG_INSTALL 1
-  )
-  set_property(TARGET ${proj} PROPERTY FOLDER "Local")
-  ExternalProject_Get_Property(${proj} install_dir)
-  set(TutorialStep5_install_dir ${install_dir})
-
-  set(proj TutorialStep5-Local-TestAfterInstall)
-  ExternalProject_Add(${proj}
-    URL "${CMAKE_CURRENT_SOURCE_DIR}/../Tutorial/Step5"
-    CMAKE_ARGS -DCMAKE_INSTALL_PREFIX:PATH=<INSTALL_DIR> -G ${CMAKE_GENERATOR} <SOURCE_DIR>
-    TEST_AFTER_INSTALL 1
-    LOG_TEST 1
-  )
-  set_property(TARGET ${proj} PROPERTY FOLDER "Local")
-endif()
-
-
-# Local TAR:
-#
-set(proj TutorialStep1-LocalTAR)
-ExternalProject_Add(${proj}
-  URL "${CMAKE_CURRENT_SOURCE_DIR}/Step1.tar"
-  URL_MD5 a87c5b47c0201c09ddfe1d5738fdb1e3
-  LIST_SEPARATOR ::
-  PATCH_COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_SOURCE_DIR}/Step1Patch.cmake
-  CMAKE_GENERATOR "${CMAKE_GENERATOR}"
-  CMAKE_ARGS -DCMAKE_INSTALL_PREFIX:PATH=<INSTALL_DIR>
-             -DTEST_LIST:STRING=A::B::C
-  INSTALL_COMMAND ""
-  LOG_CONFIGURE 1
-)
-set_property(TARGET ${proj} PROPERTY FOLDER "Local/TAR")
-
-set(proj TutorialStep1-LocalNoDirTAR)
-ExternalProject_Add(${proj}
-  URL "${CMAKE_CURRENT_SOURCE_DIR}/Step1NoDir.tar"
-  URL_MD5 d09e3d370c5c908fa035c30939ee438e
-  LIST_SEPARATOR @@
-  CMAKE_ARGS -DCMAKE_INSTALL_PREFIX:PATH=<INSTALL_DIR> -G ${CMAKE_GENERATOR} <SOURCE_DIR>
-             -DTEST_LIST:STRING=1@@2@@3
-  INSTALL_COMMAND ""
-)
-set_property(TARGET ${proj} PROPERTY FOLDER "Local/TAR")
-ExternalProject_Add_Step(${proj} mypatch
-  COMMAND ${CMAKE_COMMAND} -E echo "This is a custom external project step."
-  COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_SOURCE_DIR}/Step1Patch.cmake
-  WORKING_DIRECTORY <SOURCE_DIR>
-  DEPENDEES download
-  DEPENDERS configure
-  )
-
-
-# Local TGZ:
-#
-set(proj TutorialStep1-LocalTGZ)
-ExternalProject_Add(${proj}
-  URL "${CMAKE_CURRENT_SOURCE_DIR}/Step1.tgz"
-  URL_MD5 38c648e817339c356f6be00eeed79bd0
-  CMAKE_ARGS -DCMAKE_INSTALL_PREFIX:PATH=<INSTALL_DIR> -G ${CMAKE_GENERATOR} <SOURCE_DIR>
-  INSTALL_COMMAND ""
-  LOG_BUILD 1
-)
-set_property(TARGET ${proj} PROPERTY FOLDER "Local/TGZ")
-
-set(proj TutorialStep1-LocalNoDirTGZ)
-ExternalProject_Add(${proj}
-  URL "${CMAKE_CURRENT_SOURCE_DIR}/Step1NoDir.tgz"
-  URL_HASH SHA256=496229e2a5ed620a37c385ad9406004a18026beab8b55dd2c4565d4b7f1d5383
-  CMAKE_GENERATOR "${CMAKE_GENERATOR}"
-  CMAKE_ARGS -DCMAKE_INSTALL_PREFIX:PATH=<INSTALL_DIR>
-  INSTALL_COMMAND ""
-)
-set_property(TARGET ${proj} PROPERTY FOLDER "Local/TGZ")
-
-
-# Local BZ2:
-#
-# (The bz2 tests are here just to verify that the bz2 decompression is executed
-#  during a test suite run... The configure and build commands are set to
-#  nothing to make the test quicker. To make this more complete, I should add
-#  a diff between this and the TGZ source tree since that one does build...)
-#
-set(proj TutorialStep1-LocalBZ2)
-ExternalProject_Add(${proj}
-  URL "${CMAKE_CURRENT_SOURCE_DIR}/Step1.tar.bz2"
-  CONFIGURE_COMMAND ""
-  BUILD_COMMAND ""
-  INSTALL_COMMAND ""
-)
-set_property(TARGET ${proj} PROPERTY FOLDER "Local/BZ2")
-
-set(proj TutorialStep1-LocalNoDirBZ2)
-ExternalProject_Add(${proj}
-  URL "${CMAKE_CURRENT_SOURCE_DIR}/Step1NoDir.tar.bz2"
-  CONFIGURE_COMMAND ""
-  BUILD_COMMAND ""
-  INSTALL_COMMAND ""
-)
-set_property(TARGET ${proj} PROPERTY FOLDER "Local/BZ2")
-
-
-# Local ZIP:
-#
-# (The zip tests are here just to verify that the zip decompression is executed
-#  during a test suite run... The configure and build commands are set to
-#  nothing to make the test quicker. To make this more complete, I should add
-#  a diff between this and the TGZ source tree since that one does build...)
-#
-set(proj TutorialStep1-LocalZIP)
-ExternalProject_Add(${proj}
-  URL "${CMAKE_CURRENT_SOURCE_DIR}/Step1.zip"
-  CONFIGURE_COMMAND ""
-  BUILD_COMMAND ""
-  INSTALL_COMMAND ""
-)
-set_property(TARGET ${proj} PROPERTY FOLDER "Local/ZIP")
-
-set(proj TutorialStep1-LocalNoDirZIP)
-ExternalProject_Add(${proj}
-  URL "${CMAKE_CURRENT_SOURCE_DIR}/Step1NoDir.zip"
-  CONFIGURE_COMMAND ""
-  BUILD_COMMAND ""
-  INSTALL_COMMAND ""
-)
-set_property(TARGET ${proj} PROPERTY FOLDER "Local/ZIP")
-
-
 # CVS-based tests:
 #
 set(do_cvs_tests 0)
@@ -337,10 +176,6 @@
     INSTALL_COMMAND ""
     DEPENDS "SetupLocalCVSRepository"
     DEPENDS "EmptyNoOpProject"
-    DEPENDS "TutorialStep1-LocalTAR"
-    DEPENDS "TutorialStep1-LocalNoDirTAR"
-    DEPENDS "TutorialStep1-LocalTGZ"
-    DEPENDS "TutorialStep1-LocalNoDirTGZ"
     DEPENDS "TutorialStep1-CVS-20090626"
     DEPENDS "TutorialStep1-CVS-testtag1"
   )
@@ -537,6 +372,13 @@
   set(do_hg_tests 1)
 endif()
 
+if(do_hg_tests AND NOT UNIX)
+  if("${HG_EXECUTABLE}" MATCHES "cygwin")
+    message(STATUS "No ExternalProject hg tests with cygwin hg outside cygwin!")
+    set(do_hg_tests 0)
+  endif()
+endif()
+
 if(do_hg_tests)
   set(local_hg_repo "../../LocalRepositories/HG")
 
@@ -612,29 +454,6 @@
 #
 # BuildTree tests:
 #
-if(can_build_tutorial_step5)
-  add_test(TutorialStep5-Local-BuildTreeTest
-    "${binary_base}/TutorialStep5-Local/Tutorial" 42)
-  set_property(TEST TutorialStep5-Local-BuildTreeTest
-    APPEND PROPERTY LABELS Step5 BuildTree)
-endif()
-
-add_test(TutorialStep1-LocalTAR-BuildTreeTest
-  "${binary_base}/TutorialStep1-LocalTAR/EP-Tutorial" 36)
-set_property(TEST TutorialStep1-LocalTAR-BuildTreeTest
-  APPEND PROPERTY LABELS TAR)
-
-add_test(TutorialStep1-LocalNoDirTAR-BuildTreeTest
-  "${binary_base}/TutorialStep1-LocalNoDirTAR/EP-Tutorial" 25)
-
-add_test(TutorialStep1-LocalTGZ-BuildTreeTest
-  "${binary_base}/TutorialStep1-LocalTGZ/Tutorial" 16)
-set_property(TEST TutorialStep1-LocalTGZ-BuildTreeTest
-  APPEND PROPERTY LABELS TGZ)
-
-add_test(TutorialStep1-LocalNoDirTGZ-BuildTreeTest
-  "${binary_base}/TutorialStep1-LocalNoDirTGZ/Tutorial" 9)
-
 if(do_cvs_tests)
   add_test(TutorialStep1-CVS-20090626-BuildTreeTest
     "${binary_base}/TutorialStep1-CVS-20090626/Tutorial" 4)
@@ -669,17 +488,6 @@
 endif()
 
 
-# InstallTree tests:
-#
-if(can_build_tutorial_step5)
-  add_test(TutorialStep5-InstallTreeTest
-    "${TutorialStep5_install_dir}/bin/Tutorial" 49)
-  set_property(TEST TutorialStep5-InstallTreeTest
-    APPEND PROPERTY LABELS Step5 InstallTree)
-endif()
-
-
-message(STATUS "can_build_tutorial_step5='${can_build_tutorial_step5}'")
 message(STATUS "do_cvs_tests='${do_cvs_tests}'")
 message(STATUS "do_svn_tests='${do_svn_tests}'")
 message(STATUS "do_git_tests='${do_git_tests}' GIT_EXECUTABLE='${GIT_EXECUTABLE}'")
diff --git a/Tests/ExternalProject/TryCheckout.cmake b/Tests/ExternalProject/TryCheckout.cmake
deleted file mode 100644
index 6a396c3..0000000
--- a/Tests/ExternalProject/TryCheckout.cmake
+++ /dev/null
@@ -1,54 +0,0 @@
-find_package(CVS)
-find_package(Subversion)
-
-
-function(try_cvs_checkout repository module dir result_var)
-  # Assume cvs checkouts will not work:
-  set(${result_var} 0 PARENT_SCOPE)
-
-  if(CVS_EXECUTABLE)
-    message(STATUS "try_cvs_checkout")
-
-    # Ensure directory exists so we can call cvs in it:
-    file(MAKE_DIRECTORY "${dir}")
-
-    # Try to do the cvs checkout command:
-    execute_process(COMMAND ${CVS_EXECUTABLE} -d ${repository} co ${module}
-      WORKING_DIRECTORY ${dir}
-      TIMEOUT 30
-      RESULT_VARIABLE rv)
-
-    # If it worked, cvs checkouts will work:
-    if(rv EQUAL 0)
-      set(${result_var} 1 PARENT_SCOPE)
-    endif()
-
-    message(STATUS "try_cvs_checkout -- done")
-  endif()
-endfunction()
-
-
-function(try_svn_checkout repository dir result_var)
-  # Assume svn checkouts will not work:
-  set(${result_var} 0 PARENT_SCOPE)
-
-  if(Subversion_SVN_EXECUTABLE)
-    message(STATUS "try_svn_checkout")
-
-    # Ensure directory exists so we can call svn in it:
-    file(MAKE_DIRECTORY "${dir}")
-
-    # Try to do the svn checkout command:
-    execute_process(COMMAND ${Subversion_SVN_EXECUTABLE} co ${repository} ${dir}
-      WORKING_DIRECTORY ${dir}
-      TIMEOUT 30
-      RESULT_VARIABLE rv)
-
-    # If it worked, svn checkouts will work:
-    if(rv EQUAL 0)
-      set(${result_var} 1 PARENT_SCOPE)
-    endif()
-
-    message(STATUS "try_svn_checkout -- done")
-  endif()
-endfunction()
diff --git a/Tests/ExternalProjectLocal/CMakeLists.txt b/Tests/ExternalProjectLocal/CMakeLists.txt
new file mode 100644
index 0000000..f942197
--- /dev/null
+++ b/Tests/ExternalProjectLocal/CMakeLists.txt
@@ -0,0 +1,229 @@
+cmake_minimum_required(VERSION 2.8)
+project(ExternalProjectLocalTest NONE)
+
+include(ExternalProject)
+
+# Test ExternalProject with local projects
+
+option(ExternalProjectTest_USE_FOLDERS "Enable folder grouping in IDEs." ON)
+if(ExternalProjectTest_USE_FOLDERS)
+  set_property(GLOBAL PROPERTY USE_FOLDERS ON)
+else()
+  set_property(GLOBAL PROPERTY USE_FOLDERS OFF)
+endif()
+
+set_property(GLOBAL PROPERTY PREDEFINED_TARGETS_FOLDER
+  "CMakePredefinedTargets-in-ExternalProjectTest")
+
+set(base "${CMAKE_BINARY_DIR}/CMakeExternals")
+set(binary_base "${base}/Build")
+set_property(DIRECTORY PROPERTY EP_BASE ${base})
+set_property(DIRECTORY PROPERTY EP_STEP_TARGETS configure build test)
+
+if(NOT DEFINED can_build_tutorial_step5)
+  set(can_build_tutorial_step5 1)
+
+  # Tutorial Step5 cannot build correctly using Visual Studio 6
+  # on Windows 98 if the path of its build tree exceeds 72
+  # characters in length... So don't attempt to build it
+  # in a long path on Win98:
+  #
+  if(CMAKE_SYSTEM STREQUAL "Windows-4.10")
+    string(LENGTH "${binary_base}/TutorialStep5-Local" n)
+    if(n GREATER 72)
+      set(can_build_tutorial_step5 0)
+    endif()
+  endif()
+
+  # The ExternalProject builds of Tutorial Step5 cannot be built
+  # correctly 2nd and later times in an in-source build...
+  # (because the CMakeCache.txt from the real in-source build of
+  # the Tests/Tutorial/Step5 directory gets copied when we do
+  # the "source directory copy" step... but it still refers to
+  # its original path which yields a configure error.) So:
+  #
+  if("${CMAKE_SOURCE_DIR}" STREQUAL "${CMAKE_BINARY_DIR}")
+    set(can_build_tutorial_step5 0)
+  endif()
+endif()
+
+# Local DIR:
+#
+if(can_build_tutorial_step5)
+  set(proj TutorialStep5-Local)
+  ExternalProject_Add(${proj}
+    URL "${CMAKE_CURRENT_SOURCE_DIR}/../Tutorial/Step5"
+    CMAKE_CACHE_ARGS -DCMAKE_INSTALL_PREFIX:PATH=<INSTALL_DIR>
+    CMAKE_ARGS -G ${CMAKE_GENERATOR} <SOURCE_DIR>
+    TEST_BEFORE_INSTALL 1
+    LOG_INSTALL 1
+  )
+  set_property(TARGET ${proj} PROPERTY FOLDER "Local")
+  ExternalProject_Get_Property(${proj} install_dir)
+  set(TutorialStep5_install_dir ${install_dir})
+
+  set(proj TutorialStep5-Local-TestAfterInstall)
+  ExternalProject_Add(${proj}
+    URL "${CMAKE_CURRENT_SOURCE_DIR}/../Tutorial/Step5"
+    CMAKE_ARGS -DCMAKE_INSTALL_PREFIX:PATH=<INSTALL_DIR> -G ${CMAKE_GENERATOR} <SOURCE_DIR>
+    TEST_AFTER_INSTALL 1
+    LOG_TEST 1
+  )
+  set_property(TARGET ${proj} PROPERTY FOLDER "Local")
+endif()
+
+
+# Local TAR:
+#
+set(proj TutorialStep1-LocalTAR)
+ExternalProject_Add(${proj}
+  URL "${CMAKE_CURRENT_SOURCE_DIR}/Step1.tar"
+  URL_MD5 a87c5b47c0201c09ddfe1d5738fdb1e3
+  LIST_SEPARATOR ::
+  PATCH_COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_SOURCE_DIR}/Step1Patch.cmake
+  CMAKE_GENERATOR "${CMAKE_GENERATOR}"
+  CMAKE_ARGS -DCMAKE_INSTALL_PREFIX:PATH=<INSTALL_DIR>
+             -DTEST_LIST:STRING=A::B::C
+  INSTALL_COMMAND ""
+  LOG_CONFIGURE 1
+)
+set_property(TARGET ${proj} PROPERTY FOLDER "Local/TAR")
+
+set(proj TutorialStep1-LocalNoDirTAR)
+ExternalProject_Add(${proj}
+  URL "${CMAKE_CURRENT_SOURCE_DIR}/Step1NoDir.tar"
+  URL_MD5 d09e3d370c5c908fa035c30939ee438e
+  LIST_SEPARATOR @@
+  CMAKE_ARGS -DCMAKE_INSTALL_PREFIX:PATH=<INSTALL_DIR> -G ${CMAKE_GENERATOR} <SOURCE_DIR>
+             -DTEST_LIST:STRING=1@@2@@3
+  INSTALL_COMMAND ""
+)
+set_property(TARGET ${proj} PROPERTY FOLDER "Local/TAR")
+ExternalProject_Add_Step(${proj} mypatch
+  COMMAND ${CMAKE_COMMAND} -E echo "This is a custom external project step."
+  COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_SOURCE_DIR}/Step1Patch.cmake
+  WORKING_DIRECTORY <SOURCE_DIR>
+  DEPENDEES download
+  DEPENDERS configure
+  )
+
+
+# Local TGZ:
+#
+set(proj TutorialStep1-LocalTGZ)
+ExternalProject_Add(${proj}
+  URL "${CMAKE_CURRENT_SOURCE_DIR}/Step1.tgz"
+  URL_MD5 38c648e817339c356f6be00eeed79bd0
+  CMAKE_ARGS -DCMAKE_INSTALL_PREFIX:PATH=<INSTALL_DIR> -G ${CMAKE_GENERATOR} <SOURCE_DIR>
+  INSTALL_COMMAND ""
+  LOG_BUILD 1
+)
+set_property(TARGET ${proj} PROPERTY FOLDER "Local/TGZ")
+
+set(proj TutorialStep1-LocalNoDirTGZ)
+ExternalProject_Add(${proj}
+  URL "${CMAKE_CURRENT_SOURCE_DIR}/Step1NoDir.tgz"
+  URL_HASH SHA256=496229e2a5ed620a37c385ad9406004a18026beab8b55dd2c4565d4b7f1d5383
+  CMAKE_GENERATOR "${CMAKE_GENERATOR}"
+  CMAKE_ARGS -DCMAKE_INSTALL_PREFIX:PATH=<INSTALL_DIR>
+  INSTALL_COMMAND ""
+)
+set_property(TARGET ${proj} PROPERTY FOLDER "Local/TGZ")
+
+
+# Local BZ2:
+#
+# (The bz2 tests are here just to verify that the bz2 decompression is executed
+#  during a test suite run... The configure and build commands are set to
+#  nothing to make the test quicker. To make this more complete, I should add
+#  a diff between this and the TGZ source tree since that one does build...)
+#
+set(proj TutorialStep1-LocalBZ2)
+ExternalProject_Add(${proj}
+  URL "${CMAKE_CURRENT_SOURCE_DIR}/Step1.tar.bz2"
+  CONFIGURE_COMMAND ""
+  BUILD_COMMAND ""
+  INSTALL_COMMAND ""
+)
+set_property(TARGET ${proj} PROPERTY FOLDER "Local/BZ2")
+
+set(proj TutorialStep1-LocalNoDirBZ2)
+ExternalProject_Add(${proj}
+  URL "${CMAKE_CURRENT_SOURCE_DIR}/Step1NoDir.tar.bz2"
+  CONFIGURE_COMMAND ""
+  BUILD_COMMAND ""
+  INSTALL_COMMAND ""
+)
+set_property(TARGET ${proj} PROPERTY FOLDER "Local/BZ2")
+
+
+# Local ZIP:
+#
+# (The zip tests are here just to verify that the zip decompression is executed
+#  during a test suite run... The configure and build commands are set to
+#  nothing to make the test quicker. To make this more complete, I should add
+#  a diff between this and the TGZ source tree since that one does build...)
+#
+set(proj TutorialStep1-LocalZIP)
+ExternalProject_Add(${proj}
+  URL "${CMAKE_CURRENT_SOURCE_DIR}/Step1.zip"
+  CONFIGURE_COMMAND ""
+  BUILD_COMMAND ""
+  INSTALL_COMMAND ""
+)
+set_property(TARGET ${proj} PROPERTY FOLDER "Local/ZIP")
+
+set(proj TutorialStep1-LocalNoDirZIP)
+ExternalProject_Add(${proj}
+  URL "${CMAKE_CURRENT_SOURCE_DIR}/Step1NoDir.zip"
+  CONFIGURE_COMMAND ""
+  BUILD_COMMAND ""
+  INSTALL_COMMAND ""
+)
+set_property(TARGET ${proj} PROPERTY FOLDER "Local/ZIP")
+
+
+# Test the testable built/installed products:
+#
+enable_testing()
+
+
+# Do at least a smoke test of a built executable from each
+# project's build directory...
+#
+# BuildTree tests:
+#
+if(can_build_tutorial_step5)
+  add_test(TutorialStep5-Local-BuildTreeTest
+    "${binary_base}/TutorialStep5-Local/Tutorial" 42)
+  set_property(TEST TutorialStep5-Local-BuildTreeTest
+    APPEND PROPERTY LABELS Step5 BuildTree)
+endif()
+
+add_test(TutorialStep1-LocalTAR-BuildTreeTest
+  "${binary_base}/TutorialStep1-LocalTAR/EP-Tutorial" 36)
+set_property(TEST TutorialStep1-LocalTAR-BuildTreeTest
+  APPEND PROPERTY LABELS TAR)
+
+add_test(TutorialStep1-LocalNoDirTAR-BuildTreeTest
+  "${binary_base}/TutorialStep1-LocalNoDirTAR/EP-Tutorial" 25)
+
+add_test(TutorialStep1-LocalTGZ-BuildTreeTest
+  "${binary_base}/TutorialStep1-LocalTGZ/Tutorial" 16)
+set_property(TEST TutorialStep1-LocalTGZ-BuildTreeTest
+  APPEND PROPERTY LABELS TGZ)
+
+add_test(TutorialStep1-LocalNoDirTGZ-BuildTreeTest
+  "${binary_base}/TutorialStep1-LocalNoDirTGZ/Tutorial" 9)
+
+# InstallTree tests:
+#
+if(can_build_tutorial_step5)
+  add_test(TutorialStep5-InstallTreeTest
+    "${TutorialStep5_install_dir}/bin/Tutorial" 49)
+  set_property(TEST TutorialStep5-InstallTreeTest
+    APPEND PROPERTY LABELS Step5 InstallTree)
+endif()
+
+
+message(STATUS "can_build_tutorial_step5='${can_build_tutorial_step5}'")
diff --git a/Tests/ExternalProject/Step1.tar b/Tests/ExternalProjectLocal/Step1.tar
similarity index 100%
rename from Tests/ExternalProject/Step1.tar
rename to Tests/ExternalProjectLocal/Step1.tar
Binary files differ
diff --git a/Tests/ExternalProject/Step1.tar.bz2 b/Tests/ExternalProjectLocal/Step1.tar.bz2
similarity index 100%
rename from Tests/ExternalProject/Step1.tar.bz2
rename to Tests/ExternalProjectLocal/Step1.tar.bz2
Binary files differ
diff --git a/Tests/ExternalProject/Step1.tgz b/Tests/ExternalProjectLocal/Step1.tgz
similarity index 100%
rename from Tests/ExternalProject/Step1.tgz
rename to Tests/ExternalProjectLocal/Step1.tgz
Binary files differ
diff --git a/Tests/ExternalProject/Step1.zip b/Tests/ExternalProjectLocal/Step1.zip
similarity index 100%
rename from Tests/ExternalProject/Step1.zip
rename to Tests/ExternalProjectLocal/Step1.zip
Binary files differ
diff --git a/Tests/ExternalProject/Step1NoDir.tar b/Tests/ExternalProjectLocal/Step1NoDir.tar
similarity index 100%
rename from Tests/ExternalProject/Step1NoDir.tar
rename to Tests/ExternalProjectLocal/Step1NoDir.tar
Binary files differ
diff --git a/Tests/ExternalProject/Step1NoDir.tar.bz2 b/Tests/ExternalProjectLocal/Step1NoDir.tar.bz2
similarity index 100%
rename from Tests/ExternalProject/Step1NoDir.tar.bz2
rename to Tests/ExternalProjectLocal/Step1NoDir.tar.bz2
Binary files differ
diff --git a/Tests/ExternalProject/Step1NoDir.tgz b/Tests/ExternalProjectLocal/Step1NoDir.tgz
similarity index 100%
rename from Tests/ExternalProject/Step1NoDir.tgz
rename to Tests/ExternalProjectLocal/Step1NoDir.tgz
Binary files differ
diff --git a/Tests/ExternalProject/Step1NoDir.zip b/Tests/ExternalProjectLocal/Step1NoDir.zip
similarity index 100%
rename from Tests/ExternalProject/Step1NoDir.zip
rename to Tests/ExternalProjectLocal/Step1NoDir.zip
Binary files differ
diff --git a/Tests/ExternalProject/Step1Patch.cmake b/Tests/ExternalProjectLocal/Step1Patch.cmake
similarity index 100%
rename from Tests/ExternalProject/Step1Patch.cmake
rename to Tests/ExternalProjectLocal/Step1Patch.cmake
diff --git a/Tests/ExternalProjectUpdate/ExternalProjectUpdateTest.cmake b/Tests/ExternalProjectUpdate/ExternalProjectUpdateTest.cmake
index ea59a8e..6c7bcfe 100644
--- a/Tests/ExternalProjectUpdate/ExternalProjectUpdateTest.cmake
+++ b/Tests/ExternalProjectUpdate/ExternalProjectUpdateTest.cmake
@@ -13,6 +13,7 @@
   # Configure
   execute_process(COMMAND ${CMAKE_COMMAND}
     -G ${CMAKE_GENERATOR} -T "${CMAKE_GENERATOR_TOOLSET}"
+    -A "${CMAKE_GENERATOR_PLATFORM}"
     -DTEST_GIT_TAG:STRING=${desired_tag}
     ${ExternalProjectUpdate_SOURCE_DIR}
     WORKING_DIRECTORY ${ExternalProjectUpdate_BINARY_DIR}
diff --git a/Tests/FindPackageTest/CMakeLists.txt b/Tests/FindPackageTest/CMakeLists.txt
index 092bf20..f311fb9 100644
--- a/Tests/FindPackageTest/CMakeLists.txt
+++ b/Tests/FindPackageTest/CMakeLists.txt
@@ -374,6 +374,7 @@
 
 include(CMakePackageConfigHelpers)
 
+# Generate a config file ready to be installed.
 set(INCLUDE_INSTALL_DIR include )
 set(SHARE_INSTALL_DIR "${CMAKE_INSTALL_PREFIX}/share/" )
 set(CURRENT_BUILD_DIR "${CMAKE_CURRENT_BINARY_DIR}" )
@@ -407,6 +408,43 @@
   message(SEND_ERROR "Relocatable_FOUND set to TRUE !")
 endif()
 
+# Generate a config file for the build tree.
+set(INCLUDE_INSTALL_DIR include )
+set(SHARE_INSTALL_DIR "${CMAKE_CURRENT_BINARY_DIR}/share/" )
+set(CURRENT_BUILD_DIR "${CMAKE_CURRENT_BINARY_DIR}" )
+
+configure_package_config_file(RelocatableConfig.cmake.in "${CMAKE_CURRENT_BINARY_DIR}/RelocatableConfig.cmake"
+                              INSTALL_DESTINATION "${CMAKE_CURRENT_BINARY_DIR}"
+                              PATH_VARS INCLUDE_INSTALL_DIR SHARE_INSTALL_DIR CURRENT_BUILD_DIR
+                              INSTALL_PREFIX "${CMAKE_CURRENT_BINARY_DIR}"
+                             )
+
+set(Relocatable_FIND_COMPONENTS AComp BComp CComp)
+set(Relocatable_FIND_REQUIRED_BComp 1)
+include("${CMAKE_CURRENT_BINARY_DIR}/RelocatableConfig.cmake")
+
+if(NOT "${RELOC_INCLUDE_DIR}" STREQUAL "${CMAKE_CURRENT_BINARY_DIR}/include")
+  message(SEND_ERROR "RELOC_INCLUDE_DIR set by configure_package_config_file() is set to \"${RELOC_INCLUDE_DIR}\" (expected \"${CMAKE_CURRENT_BINARY_DIR}/include\")")
+endif()
+
+if(NOT "${RELOC_SHARE_DIR}" STREQUAL "${CMAKE_CURRENT_BINARY_DIR}/share/")
+  message(SEND_ERROR "RELOC_SHARE_DIR set by configure_package_config_file() is set to \"${RELOC_SHARE_DIR}\" (expected \"${CMAKE_CURRENT_BINARY_DIR}/share/\")")
+endif()
+
+if(NOT "${RELOC_BUILD_DIR}" STREQUAL "${CMAKE_CURRENT_BINARY_DIR}")
+  message(SEND_ERROR "RELOC_BUILD_DIR set by configure_package_config_file() is set to \"${RELOC_BUILD_DIR}\" (expected \"${CMAKE_CURRENT_BINARY_DIR}\")")
+endif()
+
+if(NOT DEFINED Relocatable_FOUND)
+  message(SEND_ERROR "Relocatable_FOUND not defined !")
+endif()
+
+if(Relocatable_FOUND)
+  message(SEND_ERROR "Relocatable_FOUND set to TRUE !")
+endif()
+
+
+
 #-----------------------------------------------------------------------------
 # Test write_basic_config_version_file().
 
diff --git a/Tests/Fortran/CMakeLists.txt b/Tests/Fortran/CMakeLists.txt
index ef3b317..1982a60 100644
--- a/Tests/Fortran/CMakeLists.txt
+++ b/Tests/Fortran/CMakeLists.txt
@@ -201,6 +201,7 @@
          --build-two-config
          --build-project ExtFort
          --build-generator ${CMAKE_GENERATOR}
+         --build-generator-platform "${CMAKE_GENERATOR_PLATFORM}"
          --build-generator-toolset "${CMAKE_GENERATOR_TOOLSET}"
          --build-options -DCMAKE_Fortran_COMPILER:STRING=${CMAKE_Fortran_COMPILER}
                          -DCMAKE_Fortran_FLAGS:STRING=${CMAKE_Fortran_FLAGS}
diff --git a/Tests/FortranC/Flags.cmake.in b/Tests/FortranC/Flags.cmake.in
index 28c38e4..2300fc6 100644
--- a/Tests/FortranC/Flags.cmake.in
+++ b/Tests/FortranC/Flags.cmake.in
@@ -15,6 +15,7 @@
 execute_process(
   WORKING_DIRECTORY "${bld}"
   COMMAND ${CMAKE_COMMAND} "${src}" -G "@CMAKE_GENERATOR@"
+                           -A "@CMAKE_GENERATOR_PLATFORM@"
                            -T "@CMAKE_GENERATOR_TOOLSET@"
                            "-DFortranC_TEST_FLAGS=1"
                            "-DCMAKE_C_COMPILER=${bld}/cc.sh"
diff --git a/Tests/FortranOnly/CMakeLists.txt b/Tests/FortranOnly/CMakeLists.txt
index d57a8b2..f55e727 100644
--- a/Tests/FortranOnly/CMakeLists.txt
+++ b/Tests/FortranOnly/CMakeLists.txt
@@ -8,13 +8,14 @@
 set_property(SOURCE world.f PROPERTY Fortran_FORMAT FREE)
 
 # create an executable that calls hello and world
-add_executable(FortranOnly testf.f)
-target_link_libraries(FortranOnly FortranOnlylib)
+add_executable(FortranOnly1 testf.f)
+set_property(TARGET FortranOnly1 PROPERTY OUTPUT_NAME FortranOnly)
+target_link_libraries(FortranOnly1 FortranOnlylib)
 
-# create a custom command that runs FortranOnly and puts
+# create a custom command that runs FortranOnly1 and puts
 # the output into the file testfhello.txt
 add_custom_command(OUTPUT ${FortranOnly_BINARY_DIR}/testfhello.txt
-  COMMAND ${FortranOnly_BINARY_DIR}/${CMAKE_CFG_INTDIR}/FortranOnly
+  COMMAND FortranOnly1
   > testfhello.txt)
 # create a second executable FortranOnly2 that has
 # testfhello.txt has an source file so that it will
@@ -27,15 +28,15 @@
   COMMAND ${CMAKE_COMMAND}
   -P ${FortranOnly_SOURCE_DIR}/checktestf2.cmake)
 
-# create a custom target that runs FortranOnly exectuable and creates
+# create a custom target that runs FortranOnly1 exectuable and creates
 # a file out.txt that should have hello world in it.
 add_custom_target(sayhello ALL
-  COMMAND ${FortranOnly_BINARY_DIR}/${CMAKE_CFG_INTDIR}/FortranOnly > out.txt
+  COMMAND FortranOnly1 > out.txt
 )
 # make sure stuff is built in the right order
 add_dependencies(checktestf2 FortranOnly2)
-add_dependencies(sayhello FortranOnly)
-add_dependencies(FortranOnly2 FortranOnly)
+add_dependencies(sayhello FortranOnly1)
+add_dependencies(FortranOnly2 FortranOnly1)
 
 # add a custom target that checkes that out.txt has the correct
 # content
@@ -43,3 +44,25 @@
   COMMAND ${CMAKE_COMMAND} -P ${FortranOnly_SOURCE_DIR}/checksayhello.cmake
   )
 add_dependencies(checksayhello sayhello)
+
+# Exclude this test on IBM XL for now because the check strangely
+# fails with 'ld: 0706-029 Use a number with the -H flag'.
+if(NOT CMAKE_Fortran_COMPILER_ID STREQUAL XL)
+  set(err_log ${CMAKE_BINARY_DIR}/CMakeFiles/CMakeError.log)
+  file(REMOVE "${err_log}")
+  include(CheckFortranSourceCompiles)
+  unset(HAVE_PRINT CACHE)
+  CHECK_Fortran_SOURCE_COMPILES([[
+      PROGRAM TEST_HAVE_PRINT
+        PRINT *, 'Hello'
+      END
+]] HAVE_PRINT)
+  if(NOT HAVE_PRINT)
+    if(EXISTS "${err_log}")
+      file(READ "${err_log}" err)
+    endif()
+    string(REPLACE "\n" "\n  " err "  ${err}")
+    message(SEND_ERROR "CHECK_Fortran_SOURCE_COMPILES for HAVE_PRINT failed:\n"
+      "${err}")
+  endif()
+endif()
diff --git a/Tests/FunctionTest/CMakeLists.txt b/Tests/FunctionTest/CMakeLists.txt
index d1fada4..68da972 100644
--- a/Tests/FunctionTest/CMakeLists.txt
+++ b/Tests/FunctionTest/CMakeLists.txt
@@ -92,7 +92,7 @@
 
 STRANGE_FUNCTION(var)
 set(second_var "second_var")
-if("${var}" STREQUAL "strange_function" AND "${second_var}" STREQUAL "second_var")
+if("x${var}" STREQUAL "xstrange_function" AND "x${second_var}" STREQUAL "xsecond_var")
   PASS("Case Test" "(${var} ${second_var})")
 else()
   FAILED("Case test" "(${var} ${second_var})")
diff --git a/Tests/InterfaceLibrary/CMakeLists.txt b/Tests/InterfaceLibrary/CMakeLists.txt
index 81b34e6..fe202dd 100644
--- a/Tests/InterfaceLibrary/CMakeLists.txt
+++ b/Tests/InterfaceLibrary/CMakeLists.txt
@@ -8,8 +8,22 @@
 
 add_subdirectory(headerdir)
 
+# Add an interface target in a subdirectory that uses an imported interface.
+add_subdirectory(ifacedir)
+
+# Poison an imported interface with the same name as that in the subdir
+# to ensure that the transitive lookup occurs in the subdir.
+add_library(imp::iface INTERFACE IMPORTED)
+set_property(TARGET imp::iface APPEND PROPERTY COMPATIBLE_INTERFACE_BOOL SOMEPROP)
+set_property(TARGET imp::iface PROPERTY INTERFACE_SOMEPROP OFF)
+set_property(TARGET imp::iface PROPERTY INTERFACE_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/does_not_exist.cpp)
+
+add_library(objlib OBJECT obj.cpp)
+add_library(iface_objlib INTERFACE)
+target_sources(iface_objlib INTERFACE $<TARGET_OBJECTS:objlib>)
+
 add_executable(InterfaceLibrary definetestexe.cpp)
-target_link_libraries(InterfaceLibrary iface_nodepends headeriface)
+target_link_libraries(InterfaceLibrary iface_nodepends headeriface subiface iface_objlib)
 
 add_subdirectory(libsdir)
 
diff --git a/Tests/InterfaceLibrary/definetestexe.cpp b/Tests/InterfaceLibrary/definetestexe.cpp
index e7a10c1..9044076 100644
--- a/Tests/InterfaceLibrary/definetestexe.cpp
+++ b/Tests/InterfaceLibrary/definetestexe.cpp
@@ -15,7 +15,10 @@
 #error Expected IFACE_HEADER_BUILDDIR
 #endif
 
+extern int obj();
+extern int sub();
+
 int main(int,char**)
 {
-  return 0;
+  return obj() + sub();
 }
diff --git a/Tests/InterfaceLibrary/ifacedir/CMakeLists.txt b/Tests/InterfaceLibrary/ifacedir/CMakeLists.txt
new file mode 100644
index 0000000..228715e
--- /dev/null
+++ b/Tests/InterfaceLibrary/ifacedir/CMakeLists.txt
@@ -0,0 +1,8 @@
+add_library(imp::iface INTERFACE IMPORTED)
+set_property(TARGET imp::iface APPEND PROPERTY COMPATIBLE_INTERFACE_BOOL SOMEPROP)
+set_property(TARGET imp::iface PROPERTY INTERFACE_SOMEPROP ON)
+set_property(TARGET imp::iface PROPERTY INTERFACE_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/sub.cpp)
+
+add_library(subiface INTERFACE)
+target_link_libraries(subiface INTERFACE imp::iface)
+set_property(TARGET subiface PROPERTY INTERFACE_SOMEPROP ON)
diff --git a/Tests/InterfaceLibrary/ifacedir/sub.cpp b/Tests/InterfaceLibrary/ifacedir/sub.cpp
new file mode 100644
index 0000000..165a66a
--- /dev/null
+++ b/Tests/InterfaceLibrary/ifacedir/sub.cpp
@@ -0,0 +1 @@
+int sub() { return 0; }
diff --git a/Tests/InterfaceLibrary/obj.cpp b/Tests/InterfaceLibrary/obj.cpp
new file mode 100644
index 0000000..ee6f5fe
--- /dev/null
+++ b/Tests/InterfaceLibrary/obj.cpp
@@ -0,0 +1 @@
+int obj() { return 0; }
diff --git a/Tests/InterfaceLinkLibraries/CMakeLists.txt b/Tests/InterfaceLinkLibraries/CMakeLists.txt
index bd0cf74..9e14c44 100644
--- a/Tests/InterfaceLinkLibraries/CMakeLists.txt
+++ b/Tests/InterfaceLinkLibraries/CMakeLists.txt
@@ -9,6 +9,9 @@
 add_library(bar_shared SHARED bar_vs6_1.cpp)
 target_compile_definitions(bar_shared INTERFACE BAR_LIBRARY)
 set_property(TARGET bar_shared APPEND PROPERTY INTERFACE_LINK_LIBRARIES foo_shared)
+add_library(zot_shared SHARED zot_vs6_1.cpp)
+target_compile_definitions(zot_shared INTERFACE ZOT_LIBRARY)
+set_property(TARGET bar_shared APPEND PROPERTY INTERFACE_LINK_LIBRARIES $<LINK_ONLY:zot_shared>)
 
 add_executable(shared_test main_vs6_1.cpp)
 set_property(TARGET shared_test APPEND PROPERTY LINK_LIBRARIES bar_shared)
@@ -18,6 +21,9 @@
 add_library(bar_static STATIC bar_vs6_2.cpp)
 target_compile_definitions(bar_static INTERFACE BAR_LIBRARY)
 set_property(TARGET bar_static APPEND PROPERTY INTERFACE_LINK_LIBRARIES foo_static)
+add_library(zot_static STATIC zot_vs6_2.cpp)
+target_compile_definitions(zot_static INTERFACE ZOT_LIBRARY)
+set_property(TARGET bar_static APPEND PROPERTY INTERFACE_LINK_LIBRARIES $<LINK_ONLY:zot_static>)
 
 add_executable(static_test main_vs6_2.cpp)
 set_property(TARGET static_test APPEND PROPERTY LINK_LIBRARIES bar_static)
@@ -31,6 +37,9 @@
 target_compile_definitions(bar_shared_private PRIVATE BAR_USE_BANG)
 set_property(TARGET bar_shared_private APPEND PROPERTY LINK_LIBRARIES bang_shared_private)
 set_property(TARGET bar_shared_private APPEND PROPERTY INTERFACE_LINK_LIBRARIES foo_shared_private)
+add_library(zot_shared_private SHARED zot_vs6_3.cpp)
+target_compile_definitions(zot_shared_private INTERFACE ZOT_LIBRARY)
+set_property(TARGET bar_shared_private APPEND PROPERTY INTERFACE_LINK_LIBRARIES $<LINK_ONLY:zot_shared_private>)
 
 add_executable(shared_private_test main_vs6_3.cpp)
 set_property(TARGET shared_private_test APPEND PROPERTY LINK_LIBRARIES bar_shared_private)
@@ -44,6 +53,9 @@
 target_compile_definitions(bar_static_private PRIVATE BAR_USE_BANG)
 set_property(TARGET bar_static_private APPEND PROPERTY LINK_LIBRARIES bang_static_private)
 set_property(TARGET bar_static_private APPEND PROPERTY INTERFACE_LINK_LIBRARIES $<LINK_ONLY:bang_static_private> foo_static_private)
+add_library(zot_static_private STATIC zot_vs6_4.cpp)
+target_compile_definitions(zot_static_private INTERFACE ZOT_LIBRARY)
+set_property(TARGET bar_static_private APPEND PROPERTY INTERFACE_LINK_LIBRARIES $<LINK_ONLY:zot_static_private>)
 
 add_executable(InterfaceLinkLibraries main_vs6_4.cpp)
 set_property(TARGET InterfaceLinkLibraries APPEND PROPERTY LINK_LIBRARIES bar_static_private)
diff --git a/Tests/InterfaceLinkLibraries/main.cpp b/Tests/InterfaceLinkLibraries/main.cpp
index a54076a..6e1295a 100644
--- a/Tests/InterfaceLinkLibraries/main.cpp
+++ b/Tests/InterfaceLinkLibraries/main.cpp
@@ -11,9 +11,13 @@
 #error Unexpected BANG_LIBRARY
 #endif
 
-#include "bar.h"
+#ifdef ZOT_LIBRARY
+#error Unexpected ZOT_LIBRARY
+#endif
+
+#include "zot.h"
 
 int main(void)
 {
-  return foo() + bar();
+  return foo() + bar() + zot();
 }
diff --git a/Tests/InterfaceLinkLibraries/zot.cpp b/Tests/InterfaceLinkLibraries/zot.cpp
new file mode 100644
index 0000000..69462b0
--- /dev/null
+++ b/Tests/InterfaceLinkLibraries/zot.cpp
@@ -0,0 +1,6 @@
+#include "zot.h"
+
+int zot()
+{
+  return 0;
+}
diff --git a/Tests/InterfaceLinkLibraries/zot.h b/Tests/InterfaceLinkLibraries/zot.h
new file mode 100644
index 0000000..5e4fb1e
--- /dev/null
+++ b/Tests/InterfaceLinkLibraries/zot.h
@@ -0,0 +1,7 @@
+
+#include "bar.h"
+
+#ifdef _WIN32
+__declspec(dllexport)
+#endif
+int zot();
diff --git a/Tests/InterfaceLinkLibraries/zot_vs6_1.cpp b/Tests/InterfaceLinkLibraries/zot_vs6_1.cpp
new file mode 100644
index 0000000..c588c5f
--- /dev/null
+++ b/Tests/InterfaceLinkLibraries/zot_vs6_1.cpp
@@ -0,0 +1 @@
+#include "zot.cpp"
diff --git a/Tests/InterfaceLinkLibraries/zot_vs6_2.cpp b/Tests/InterfaceLinkLibraries/zot_vs6_2.cpp
new file mode 100644
index 0000000..c588c5f
--- /dev/null
+++ b/Tests/InterfaceLinkLibraries/zot_vs6_2.cpp
@@ -0,0 +1 @@
+#include "zot.cpp"
diff --git a/Tests/InterfaceLinkLibraries/zot_vs6_3.cpp b/Tests/InterfaceLinkLibraries/zot_vs6_3.cpp
new file mode 100644
index 0000000..c588c5f
--- /dev/null
+++ b/Tests/InterfaceLinkLibraries/zot_vs6_3.cpp
@@ -0,0 +1 @@
+#include "zot.cpp"
diff --git a/Tests/InterfaceLinkLibraries/zot_vs6_4.cpp b/Tests/InterfaceLinkLibraries/zot_vs6_4.cpp
new file mode 100644
index 0000000..c588c5f
--- /dev/null
+++ b/Tests/InterfaceLinkLibraries/zot_vs6_4.cpp
@@ -0,0 +1 @@
+#include "zot.cpp"
diff --git a/Tests/JacocoCoverage/Coverage/src/main/java/org/cmake/CoverageTest.java b/Tests/JacocoCoverage/Coverage/src/main/java/org/cmake/CoverageTest.java
new file mode 100644
index 0000000..4fb43c6
--- /dev/null
+++ b/Tests/JacocoCoverage/Coverage/src/main/java/org/cmake/CoverageTest.java
@@ -0,0 +1,52 @@
+package org.cmake.Coverage;
+
+import java.io.Serializable;
+import java.util.Map;
+import java.util.List;
+import java.awt.*;
+
+public class CoverageTest {
+
+  public static String VarOne = "test1";
+  public static String VarTwo = "test2";
+  private Integer IntOne = 4;
+
+  public static Boolean equalsVarOne(String inString) {
+
+    if(VarOne.equals(inString)){
+      return true;
+    }
+    else {
+      return false;
+    }
+  }
+
+  public static boolean equalsVarTwo(String inString){
+
+    if(VarTwo.equals(inString)){
+      return true;
+    }
+    else {
+      return false;
+    }
+  }
+
+  private Integer timesIntOne(Integer inVal){
+
+    return inVal * IntOne;
+  }
+
+  public static boolean whileLoop(Integer StopInt){
+
+    Integer i = 0;
+    while(i < StopInt){
+      i=i+1;
+    }
+    if (i.equals(5)){
+     return true;
+    }
+    else {
+     return false;
+    }
+  }
+}
diff --git a/Tests/JacocoCoverage/Coverage/target/site/jacoco.xml b/Tests/JacocoCoverage/Coverage/target/site/jacoco.xml
new file mode 100644
index 0000000..49c3e87
--- /dev/null
+++ b/Tests/JacocoCoverage/Coverage/target/site/jacoco.xml
@@ -0,0 +1 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?><!DOCTYPE report PUBLIC "-//JACOCO//DTD Report 1.0//EN" "report.dtd"><report name="Coverage"><sessioninfo id="vagrant-ubuntu-precise-32-f1c264e9" start="1402427058670" dump="1402427059269"/><package name="org/cmake"><class name="org/cmake/Coverage/CoverageTest"><method name="&lt;init&gt;" desc="()V" line="8"><counter type="INSTRUCTION" missed="7" covered="0"/><counter type="LINE" missed="2" covered="0"/><counter type="COMPLEXITY" missed="1" covered="0"/><counter type="METHOD" missed="1" covered="0"/></method><method name="equalsVarOne" desc="(Ljava/lang/String;)Ljava/lang/Boolean;" line="16"><counter type="INSTRUCTION" missed="3" covered="7"/><counter type="BRANCH" missed="1" covered="1"/><counter type="LINE" missed="1" covered="2"/><counter type="COMPLEXITY" missed="1" covered="1"/><counter type="METHOD" missed="0" covered="1"/></method><method name="equalsVarTwo" desc="(Ljava/lang/String;)Z" line="26"><counter type="INSTRUCTION" missed="0" covered="8"/><counter type="BRANCH" missed="0" covered="2"/><counter type="LINE" missed="0" covered="3"/><counter type="COMPLEXITY" missed="0" covered="2"/><counter type="METHOD" missed="0" covered="1"/></method><method name="timesIntOne" desc="(Ljava/lang/Integer;)Ljava/lang/Integer;" line="36"><counter type="INSTRUCTION" missed="8" covered="0"/><counter type="LINE" missed="1" covered="0"/><counter type="COMPLEXITY" missed="1" covered="0"/><counter type="METHOD" missed="1" covered="0"/></method><method name="whileLoop" desc="(Ljava/lang/Integer;)Z" line="41"><counter type="INSTRUCTION" missed="0" covered="24"/><counter type="BRANCH" missed="0" covered="4"/><counter type="LINE" missed="0" covered="6"/><counter type="COMPLEXITY" missed="0" covered="3"/><counter type="METHOD" missed="0" covered="1"/></method><method name="&lt;clinit&gt;" desc="()V" line="10"><counter type="INSTRUCTION" missed="0" covered="5"/><counter type="LINE" missed="0" covered="2"/><counter type="COMPLEXITY" missed="0" covered="1"/><counter type="METHOD" missed="0" covered="1"/></method><counter type="INSTRUCTION" missed="18" covered="44"/><counter type="BRANCH" missed="1" covered="7"/><counter type="LINE" missed="4" covered="13"/><counter type="COMPLEXITY" missed="3" covered="7"/><counter type="METHOD" missed="2" covered="4"/><counter type="CLASS" missed="0" covered="1"/></class><sourcefile name="CoverageTest.java"><line nr="8" mi="2" ci="0" mb="0" cb="0"/><line nr="10" mi="0" ci="2" mb="0" cb="0"/><line nr="11" mi="0" ci="3" mb="0" cb="0"/><line nr="12" mi="5" ci="0" mb="0" cb="0"/><line nr="16" mi="0" ci="4" mb="1" cb="1"/><line nr="17" mi="0" ci="3" mb="0" cb="0"/><line nr="20" mi="3" ci="0" mb="0" cb="0"/><line nr="26" mi="0" ci="4" mb="0" cb="2"/><line nr="27" mi="0" ci="2" mb="0" cb="0"/><line nr="30" mi="0" ci="2" mb="0" cb="0"/><line nr="36" mi="8" ci="0" mb="0" cb="0"/><line nr="41" mi="0" ci="3" mb="0" cb="0"/><line nr="42" mi="0" ci="5" mb="0" cb="2"/><line nr="43" mi="0" ci="7" mb="0" cb="0"/><line nr="45" mi="0" ci="5" mb="0" cb="2"/><line nr="46" mi="0" ci="2" mb="0" cb="0"/><line nr="49" mi="0" ci="2" mb="0" cb="0"/><counter type="INSTRUCTION" missed="18" covered="44"/><counter type="BRANCH" missed="1" covered="7"/><counter type="LINE" missed="4" covered="13"/><counter type="COMPLEXITY" missed="3" covered="7"/><counter type="METHOD" missed="2" covered="4"/><counter type="CLASS" missed="0" covered="1"/></sourcefile><counter type="INSTRUCTION" missed="18" covered="44"/><counter type="BRANCH" missed="1" covered="7"/><counter type="LINE" missed="4" covered="13"/><counter type="COMPLEXITY" missed="3" covered="7"/><counter type="METHOD" missed="2" covered="4"/><counter type="CLASS" missed="0" covered="1"/></package><counter type="INSTRUCTION" missed="18" covered="44"/><counter type="BRANCH" missed="1" covered="7"/><counter type="LINE" missed="4" covered="13"/><counter type="COMPLEXITY" missed="3" covered="7"/><counter type="METHOD" missed="2" covered="4"/><counter type="CLASS" missed="0" covered="1"/></report>
diff --git a/Tests/JacocoCoverage/DartConfiguration.tcl.in b/Tests/JacocoCoverage/DartConfiguration.tcl.in
new file mode 100644
index 0000000..cc10e9c
--- /dev/null
+++ b/Tests/JacocoCoverage/DartConfiguration.tcl.in
@@ -0,0 +1,8 @@
+# This file is configured by CMake automatically as DartConfiguration.tcl
+# If you choose not to use CMake, this file may be hand configured, by
+# filling in the required variables.
+
+
+# Configuration directories and files
+SourceDirectory: ${CMake_BINARY_DIR}/Testing/JacocoCoverage
+BuildDirectory: ${CMake_BINARY_DIR}/Testing/JacocoCoverage
diff --git a/Tests/LoadCommand/CMakeLists.txt b/Tests/LoadCommand/CMakeLists.txt
index c933798..03a3b49 100644
--- a/Tests/LoadCommand/CMakeLists.txt
+++ b/Tests/LoadCommand/CMakeLists.txt
@@ -8,10 +8,6 @@
 CHECK_TYPE_SIZE(char  SIZEOF_CHAR)
 CHECK_TYPE_SIZE(short  SIZEOF_SHORT)
 
-include (CheckFunctionExists)
-CHECK_FUNCTION_EXISTS(printf        HAVE_PRINTF)
-CHECK_FUNCTION_EXISTS(vsblabla      HAVE_VSBLABLA)
-
 configure_file(${LoadCommand_SOURCE_DIR}/LoadedCommand.h.in
                ${LoadCommand_BINARY_DIR}/LoadedCommand.h)
 
diff --git a/Tests/LoadCommand/LoadedCommand.cxx.in b/Tests/LoadCommand/LoadedCommand.cxx.in
index c58bcf1..72ec014 100644
--- a/Tests/LoadCommand/LoadedCommand.cxx.in
+++ b/Tests/LoadCommand/LoadedCommand.cxx.in
@@ -9,15 +9,6 @@
 int main ()
 {
   int ret = 0;
-#ifdef HAVE_VSBLABLA
-  printf("Should not be able to find vsblabla\n");
-  ret = 1;
-#endif
-
-#if !defined( HAVE_PRINTF )
-  printf("Should be able to find printf\n");
-  ret= 1;
-#endif
 
 #if !defined( ADDED_DEFINITION )
   printf("Should have ADDED_DEFINITION defined\n");
diff --git a/Tests/LoadCommand/LoadedCommand.h.in b/Tests/LoadCommand/LoadedCommand.h.in
index 7516a66..733c414 100644
--- a/Tests/LoadCommand/LoadedCommand.h.in
+++ b/Tests/LoadCommand/LoadedCommand.h.in
@@ -1,7 +1,3 @@
 /* Check for size of types */
 #cmakedefine SIZEOF_CHAR      ${SIZEOF_CHAR}
 #cmakedefine SIZEOF_SHORT      ${SIZEOF_SHORT}
-
-/* Check for functions */
-#cmakedefine HAVE_PRINTF
-#cmakedefine HAVE_VSBLABLA
diff --git a/Tests/LoadCommandOneConfig/CMakeLists.txt b/Tests/LoadCommandOneConfig/CMakeLists.txt
index a75ad5a..6affd34 100644
--- a/Tests/LoadCommandOneConfig/CMakeLists.txt
+++ b/Tests/LoadCommandOneConfig/CMakeLists.txt
@@ -8,10 +8,6 @@
 CHECK_TYPE_SIZE(char  SIZEOF_CHAR)
 CHECK_TYPE_SIZE(short  SIZEOF_SHORT)
 
-include (CheckFunctionExists)
-CHECK_FUNCTION_EXISTS(printf        HAVE_PRINTF)
-CHECK_FUNCTION_EXISTS(vsblabla      HAVE_VSBLABLA)
-
 include (${CMAKE_ROOT}/Modules/CheckIncludeFile.cmake)
 CHECK_INCLUDE_FILE("sys/prctl.h"    HAVE_SYS_PRCTL_H)
 
diff --git a/Tests/LoadCommandOneConfig/LoadedCommand.cxx.in b/Tests/LoadCommandOneConfig/LoadedCommand.cxx.in
index c58bcf1..72ec014 100644
--- a/Tests/LoadCommandOneConfig/LoadedCommand.cxx.in
+++ b/Tests/LoadCommandOneConfig/LoadedCommand.cxx.in
@@ -9,15 +9,6 @@
 int main ()
 {
   int ret = 0;
-#ifdef HAVE_VSBLABLA
-  printf("Should not be able to find vsblabla\n");
-  ret = 1;
-#endif
-
-#if !defined( HAVE_PRINTF )
-  printf("Should be able to find printf\n");
-  ret= 1;
-#endif
 
 #if !defined( ADDED_DEFINITION )
   printf("Should have ADDED_DEFINITION defined\n");
diff --git a/Tests/LoadCommandOneConfig/LoadedCommand.h.in b/Tests/LoadCommandOneConfig/LoadedCommand.h.in
index 7a0a15d..d748d06 100644
--- a/Tests/LoadCommandOneConfig/LoadedCommand.h.in
+++ b/Tests/LoadCommandOneConfig/LoadedCommand.h.in
@@ -2,10 +2,6 @@
 #cmakedefine SIZEOF_CHAR      ${SIZEOF_CHAR}
 #cmakedefine SIZEOF_SHORT      ${SIZEOF_SHORT}
 
-/* Check for functions */
-#cmakedefine HAVE_PRINTF
-#cmakedefine HAVE_VSBLABLA
-
 /* Check for headers */
 #cmakedefine HAVE_SYS_PRCTL_H
 
diff --git a/Tests/MacRuntimePath/CMakeLists.txt b/Tests/MacRuntimePath/CMakeLists.txt
index eeb3653..3e9ab8a 100644
--- a/Tests/MacRuntimePath/CMakeLists.txt
+++ b/Tests/MacRuntimePath/CMakeLists.txt
@@ -39,6 +39,7 @@
     --build-project MacRuntimePath_A
     --build-target install
     --build-generator ${CMAKE_GENERATOR}
+    --build-generator-platform "${CMAKE_GENERATOR_PLATFORM}"
     --build-generator-toolset "${CMAKE_GENERATOR_TOOLSET}"
     --build-options -C${MacRuntimePath_BINARY_DIR}/InitialCache.cmake
   VERBATIM
@@ -60,6 +61,7 @@
    --build-noclean
    --build-project MacRuntimePath_B
    --build-generator ${CMAKE_GENERATOR}
+   --build-generator-platform "${CMAKE_GENERATOR_PLATFORM}"
    --build-generator-toolset "${CMAKE_GENERATOR_TOOLSET}"
    --build-options -C${MacRuntimePath_BINARY_DIR}/InitialCache.cmake
   VERBATIM
diff --git a/Tests/MacroTest/CMakeLists.txt b/Tests/MacroTest/CMakeLists.txt
index 02bb31f..6c6dfb6 100644
--- a/Tests/MacroTest/CMakeLists.txt
+++ b/Tests/MacroTest/CMakeLists.txt
@@ -36,7 +36,7 @@
 endmacro()
 STRANGE_MACRO(var)
 set(second_var "second_var")
-if("${var}" STREQUAL "strange_macro" AND "${second_var}" STREQUAL "second_var")
+if("x${var}" STREQUAL "xstrange_macro" AND "x${second_var}" STREQUAL "xsecond_var")
   PASS("Case Test" "(${var} ${second_var})")
 else()
   FAILED("Case test" "(${var} ${second_var})")
diff --git a/Tests/Module/WriteCompilerDetectionHeader/CMakeLists.txt b/Tests/Module/WriteCompilerDetectionHeader/CMakeLists.txt
index ab0ebc3..645cc65 100644
--- a/Tests/Module/WriteCompilerDetectionHeader/CMakeLists.txt
+++ b/Tests/Module/WriteCompilerDetectionHeader/CMakeLists.txt
@@ -35,6 +35,10 @@
   return()
 endif()
 
+string(REGEX REPLACE "^([0-9]+)\\.[0-9]+\\.[0-9]+.*" "\\1" COMPILER_VERSION_MAJOR "${CMAKE_CXX_COMPILER_VERSION}")
+string(REGEX REPLACE "^[0-9]+\\.([0-9]+)\\.[0-9]+.*" "\\1" COMPILER_VERSION_MINOR "${CMAKE_CXX_COMPILER_VERSION}")
+string(REGEX REPLACE "^[0-9]+\\.[0-9]+\\.([0-9]+).*" "\\1" COMPILER_VERSION_PATCH "${CMAKE_CXX_COMPILER_VERSION}")
+
 macro(set_defines target true_defs false_defs)
   set(defines)
   foreach(def ${true_defs})
@@ -46,6 +50,9 @@
   target_compile_definitions(${target}
     PRIVATE
       ${defines}
+      EXPECTED_COMPILER_VERSION_MAJOR=${COMPILER_VERSION_MAJOR}
+      EXPECTED_COMPILER_VERSION_MINOR=${COMPILER_VERSION_MINOR}
+      EXPECTED_COMPILER_VERSION_PATCH=${COMPILER_VERSION_PATCH}
   )
 endmacro()
 
diff --git a/Tests/Module/WriteCompilerDetectionHeader/main.cpp b/Tests/Module/WriteCompilerDetectionHeader/main.cpp
index 8b4ea52..b807ad5 100644
--- a/Tests/Module/WriteCompilerDetectionHeader/main.cpp
+++ b/Tests/Module/WriteCompilerDetectionHeader/main.cpp
@@ -13,6 +13,18 @@
 #error cxx_variadic_templates expected availability did not match.
 #endif
 
+#if !CHECK(VERSION_MAJOR)
+#error Compiler major version did not match.
+#endif
+
+#if !CHECK(VERSION_MINOR)
+#error Compiler minor version did not match.
+#endif
+
+#if !CHECK(VERSION_PATCH)
+#error Compiler patch version did not match.
+#endif
+
 int main()
 {
   return 0;
diff --git a/Tests/MumpsCoverage/VistA-FOIA/Packages/Uncategorized/ZZCOVTST.m b/Tests/MumpsCoverage/VistA-FOIA/Packages/Uncategorized/ZZCOVTST.m
index 9a08edf..ee70682 100644
--- a/Tests/MumpsCoverage/VistA-FOIA/Packages/Uncategorized/ZZCOVTST.m
+++ b/Tests/MumpsCoverage/VistA-FOIA/Packages/Uncategorized/ZZCOVTST.m
@@ -10,6 +10,7 @@
  I '$$T5 W "RETURNED FROM t5",!
  Q
  ; This line not executable
+ D T6^ZZCOVTST
  ;
 T1 ; This line should always be found
  N D
@@ -33,4 +34,10 @@
 T5(EQ) ;this entry point is called with a $$ notation
  W "THIS IS THE $$ NOTATION!",!
  Q 0
+T6 ; An entry point to show comments inside of "DO" blocks
+ D
+ . W "This is executable code",!
+ . ;This is a comment inside the do block, not executable
+ . S ZZBLAH="blah"
+ W "Ending T6",!
  ;
diff --git a/Tests/MumpsCoverage/ZZCOVTST.cmcov b/Tests/MumpsCoverage/ZZCOVTST.cmcov
index 798e5b2..7a5df61 100644
--- a/Tests/MumpsCoverage/ZZCOVTST.cmcov
+++ b/Tests/MumpsCoverage/ZZCOVTST.cmcov
@@ -1,5 +1,5 @@
 Routine,Line,RtnLine,Code

-ZZCOVTST,1,0,"ZZCOVTST;OSEHRA/JPS -- Test routine for Coverage Parsing;4/28/2014"

+ZZCOVTST,1,1,"ZZCOVTST;OSEHRA/JPS -- Test routine for Coverage Parsing;4/28/2014"

 ,2,0," ; (tab) This is series of comments"

 ,3,0," ; (tab) it should all be not executable"

 ,4,0,"        ; (spaces) one of these sets might be a problem"

@@ -8,31 +8,38 @@
 ,7,1," N D"

 ,8,1," S D=1 ;An executable line"

 ,9,1," D T1^ZZCOVTST"

-,10,1,"I '$$T5 W ""RETURNED FROM t5"",!"

-,11,1," Q"

-,12,0," ; This line not executable"

-,13,0," ;"

-,14,0,"T1 ; This line should always be found"

-,15,1," N D"

-,16,1," S D=2"

-,17,1," W !,D,!,""This is the second entry point"",!"

-,18,1," D T2^ZZCOVTST(D)"

-,19,1," Q"

-,20,0," ;"

-,21,0,"T2(EQ) ; This is debatable"

-,22,1," N D"

-,23,1," S D=3"

-,24,1," W !,D,!,EQ,""This is the third entry point"",!"

-,25,1," D T3^ZZCOVTST"

-,26,1," Q"

-,27,0," ;"

-,28,1,"T3  N D S D=4 W D,!,""Fourth Entry point"",! Q"

-,29,0," ;"

-,30,0,"T4  N D S D=5 W ""Shouldn't be executed"""

-,31,0," W ""Lots to not do"""

-,32,0," Q"

-,33,1,"T5()"

-,34,1," W ""THIS IS ONE WITH $$ NOTATION"",1"

-,35,1," Q 0"

-,36,0," ;"

-Totals for ZZCOVTST,,19,

+,10,1," I '$$T5 W ""RETURNED FROM t5"",!"

+,11,1," D T6^ZZCOVTST"

+,12,1," Q"

+,13,0," ; This line not executable"

+,14,0," ;"

+,15,0,"T1 ; This line should always be found"

+,16,1," N D"

+,17,1," S D=2"

+,18,1," W !,D,!,""This is the second entry point"",!"

+,19,1," D T2^ZZCOVTST(D)"

+,20,1," Q"

+,21,0," ;"

+,22,0,"T2(EQ) ; This is debatable and only called with ENT^ROU notation"

+,23,1," N D"

+,24,1," S D=3"

+,25,1," W !,D,!,EQ,""This is the third entry point"",!"

+,26,1," D T3^ZZCOVTST"

+,27,1," Q"

+,28,0," ;"

+,29,1,"T3  N D S D=4 W D,!,""Fourth Entry point"",! Q"

+,30,0," ;"

+,31,0,"T4  N D S D=5 W ""Shouldn't be executed"""

+,32,0," W ""Lots to not do"""

+,33,0," Q"

+,34,1,"T5(EQ) ;this entry point is called with a $$ notation"

+,35,1," W ""THIS IS THE $$ NOTATION!"",!"

+,36,1," Q 0"

+,37,0,"T6 ; An entry point to show comments inside of ""DO"" blocks"

+,38,1," D"

+,39,1," . W ""This is executable code"",!"

+,40,0," . ; This is a comment inside the do block, not executable"

+,41,1," . S ZZBLAH=""blah"""

+,42,1," W ""Ending T6"",!"

+,43,0," ;"

+Totals for ZZCOVTST,,25,
\ No newline at end of file
diff --git a/Tests/MumpsCoverage/ZZCOVTST.mcov b/Tests/MumpsCoverage/ZZCOVTST.mcov
index f73d354..b2608d9 100644
--- a/Tests/MumpsCoverage/ZZCOVTST.mcov
+++ b/Tests/MumpsCoverage/ZZCOVTST.mcov
@@ -1,30 +1,38 @@
 %GO Global Output Utility
-GT.M 30-APR-2014 14:24:46 ZWR
-^ZZCOVERAGE("*CHILDREN")="0:0:0"
-^ZZCOVERAGE("*RUN")="24000:88000:112000"
-^ZZCOVERAGE("ZZCOVTST","EN")="1:4000:8000:12000:6464583"
-^ZZCOVERAGE("ZZCOVTST","EN",1)="1:0:0:0:20"
-^ZZCOVERAGE("ZZCOVTST","EN",2)="1:0:0:0:14"
-^ZZCOVERAGE("ZZCOVTST","EN",3)="1:0:0:0:26"
-^ZZCOVERAGE("ZZCOVTST","EN",4)="1:0:0:0:228"
-^ZZCOVERAGE("ZZCOVTST","T1")="1:0:0:0:92"
-^ZZCOVERAGE("ZZCOVTST","T1",1)="1:0:0:0:13"
-^ZZCOVERAGE("ZZCOVTST","T1",2)="1:0:0:0:12"
-^ZZCOVERAGE("ZZCOVTST","T1",3)="1:0:0:0:14"
-^ZZCOVERAGE("ZZCOVTST","T1",4)="1:0:0:0:29"
-^ZZCOVERAGE("ZZCOVTST","T1",5)="1:0:0:0:12"
-^ZZCOVERAGE("ZZCOVTST","T2")="1:0:0:0:102"
-^ZZCOVERAGE("ZZCOVTST","T2",0)="1:0:0:0:14"
-^ZZCOVERAGE("ZZCOVTST","T2",1)="1:0:0:0:12"
-^ZZCOVERAGE("ZZCOVTST","T2",2)="1:0:0:0:12"
-^ZZCOVERAGE("ZZCOVTST","T2",3)="1:0:0:0:14"
-^ZZCOVERAGE("ZZCOVTST","T2",4)="1:0:0:0:25"
-^ZZCOVERAGE("ZZCOVTST","T2",5)="1:0:0:0:12"
-^ZZCOVERAGE("ZZCOVTST","T3")="1:0:0:0:28"
-^ZZCOVERAGE("ZZCOVTST","T3",0)="1:0:0:0:17"
-^ZZCOVERAGE("ZZCOVTST","T5")="1:0:0:0:388"
-^ZZCOVERAGE("ZZCOVTST","T5",0)="1:0:0:0:114"
-^ZZCOVERAGE("ZZCOVTST","T5",1)="1:0:0:0:28"
-^ZZCOVERAGE("ZZCOVTST","T5",2)="1:0:0:0:14"
+GT.M 15-AUG-2014 10:14:32 ZWR
+^ZZCOVERAGE("*CHILDREN")="212000:68000:280000"
+^ZZCOVERAGE("*RUN")="56000:136000:192000"
+^ZZCOVERAGE("ZZCOVTST","EN")="1:4000:4000:8000:8627798"
+^ZZCOVERAGE("ZZCOVTST","EN",1)="1:0:0:0:27"
+^ZZCOVERAGE("ZZCOVTST","EN",2)="1:0:0:0:23"
+^ZZCOVERAGE("ZZCOVTST","EN",3)="1:0:0:0:70"
+^ZZCOVERAGE("ZZCOVTST","EN",4)="1:0:0:0:74"
+^ZZCOVERAGE("ZZCOVTST","EN",5)="1:0:0:0:66"
+^ZZCOVERAGE("ZZCOVTST","EN",6)="1:0:0:0:40"
+^ZZCOVERAGE("ZZCOVTST","T1")="1:0:0:0:208"
+^ZZCOVERAGE("ZZCOVTST","T1",1)="1:0:0:0:23"
+^ZZCOVERAGE("ZZCOVTST","T1",2)="1:0:0:0:24"
+^ZZCOVERAGE("ZZCOVTST","T1",3)="1:0:0:0:26"
+^ZZCOVERAGE("ZZCOVTST","T1",4)="1:0:0:0:73"
+^ZZCOVERAGE("ZZCOVTST","T1",5)="1:0:0:0:40"
+^ZZCOVERAGE("ZZCOVTST","T2")="1:0:0:0:1783"
+^ZZCOVERAGE("ZZCOVTST","T2",0)="1:0:0:0:25"
+^ZZCOVERAGE("ZZCOVTST","T2",1)="1:0:0:0:524"
+^ZZCOVERAGE("ZZCOVTST","T2",2)="1:0:0:0:40"
+^ZZCOVERAGE("ZZCOVTST","T2",3)="1:0:0:0:95"
+^ZZCOVERAGE("ZZCOVTST","T2",4)="1:0:0:0:607"
+^ZZCOVERAGE("ZZCOVTST","T2",5)="1:0:0:0:470"
+^ZZCOVERAGE("ZZCOVTST","T3")="1:0:0:0:254"
+^ZZCOVERAGE("ZZCOVTST","T3",0)="1:0:0:0:76"
+^ZZCOVERAGE("ZZCOVTST","T5")="1:0:0:0:153"
+^ZZCOVERAGE("ZZCOVTST","T5",0)="1:0:0:0:40"
+^ZZCOVERAGE("ZZCOVTST","T5",1)="1:0:0:0:41"
+^ZZCOVERAGE("ZZCOVTST","T5",2)="1:0:0:0:41"
+^ZZCOVERAGE("ZZCOVTST","T6")="1:0:0:0:227"
+^ZZCOVERAGE("ZZCOVTST","T6",1)="1:0:0:0:41"
+^ZZCOVERAGE("ZZCOVTST","T6",2)="1:0:0:0:42"
+^ZZCOVERAGE("ZZCOVTST","T6",4)="1:0:0:0:41"
+^ZZCOVERAGE("ZZCOVTST","T6",5)="1:0:0:0:34"
+^ZZCOVERAGE("ZZCOVTST","T6",6)="1:0:0:0:38"
 
 
diff --git a/Tests/ObjectLibrary/A/CMakeLists.txt b/Tests/ObjectLibrary/A/CMakeLists.txt
index 55778ea..c24c5ed 100644
--- a/Tests/ObjectLibrary/A/CMakeLists.txt
+++ b/Tests/ObjectLibrary/A/CMakeLists.txt
@@ -1,18 +1,26 @@
 project(ObjectLibraryA C)
 # Add -fPIC so objects can be used in shared libraries.
-# TODO: Need property for this.
-if(CMAKE_SHARED_LIBRARY_C_FLAGS AND NOT WATCOM)
-  set(CMAKE_C_FLAGS "${CMAKE_SHARED_LIBRARY_C_FLAGS} ${CMAKE_C_FLAGS}")
-endif()
+set(CMAKE_POSITION_INDEPENDENT_CODE ON)
 
 add_definitions(-DA_DEF)
 
 add_custom_command(
   OUTPUT a1.c
-  DEPENDS a1.c.in
+  DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/a1.c.in
   COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/a1.c.in
                                    ${CMAKE_CURRENT_BINARY_DIR}/a1.c
   )
 
-add_library(A OBJECT a1.c a2.c)
+# Remove the custom command output to be sure it runs in an
+# incremental test.  Skip this on VS 6 because it sometimes
+# re-runs CMake after the custom command runs.
+if(NOT CMAKE_GENERATOR STREQUAL "Visual Studio 6")
+  file(REMOVE ${CMAKE_CURRENT_BINARY_DIR}/a.cmake)
+endif()
+add_custom_command(
+  OUTPUT a.cmake
+  COMMAND ${CMAKE_COMMAND} -E touch ${CMAKE_CURRENT_BINARY_DIR}/a.cmake
+  )
+
+add_library(A OBJECT a1.c a2.c a.cmake)
 target_include_directories(A PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
diff --git a/Tests/ObjectLibrary/B/CMakeLists.txt b/Tests/ObjectLibrary/B/CMakeLists.txt
index a567f96..2158084 100644
--- a/Tests/ObjectLibrary/B/CMakeLists.txt
+++ b/Tests/ObjectLibrary/B/CMakeLists.txt
@@ -5,10 +5,7 @@
 endif()
 
 # Add -fPIC so objects can be used in shared libraries.
-# TODO: Need property for this.
-if(CMAKE_SHARED_LIBRARY_C_FLAGS AND NOT WATCOM)
-  set(CMAKE_C_FLAGS "${CMAKE_SHARED_LIBRARY_C_FLAGS} ${CMAKE_C_FLAGS}")
-endif()
+set(CMAKE_POSITION_INDEPENDENT_CODE ON)
 
 add_library(B OBJECT b1.c b2.c)
 target_include_directories(B PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
diff --git a/Tests/ObjectLibrary/CMakeLists.txt b/Tests/ObjectLibrary/CMakeLists.txt
index 0aeefaa..e9f553e 100644
--- a/Tests/ObjectLibrary/CMakeLists.txt
+++ b/Tests/ObjectLibrary/CMakeLists.txt
@@ -12,6 +12,7 @@
 add_executable(UseCshared main.c)
 set_property(TARGET UseCshared PROPERTY COMPILE_DEFINITIONS SHARED_C)
 target_link_libraries(UseCshared Cshared)
+add_custom_command(TARGET UseCshared POST_BUILD COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_BINARY_DIR}/A/a.cmake)
 
 add_executable(UseCinternal main.c c.c $<TARGET_OBJECTS:A> $<TARGET_OBJECTS:B>)
 
@@ -59,4 +60,10 @@
   $<TARGET_OBJECTS:ABmain> $<TARGET_OBJECTS:A> $<TARGET_OBJECTS:B>
   )
 
+# Test target-level dependencies of executable without sources.
+file(REMOVE ${CMAKE_CURRENT_BINARY_DIR}/UseABinternalDep.cmake)
+add_custom_target(UseABinternalDep COMMAND ${CMAKE_COMMAND} -E touch UseABinternalDep.cmake)
+add_custom_command(TARGET UseABinternal POST_BUILD COMMAND ${CMAKE_COMMAND} -P UseABinternalDep.cmake)
+add_dependencies(UseABinternal UseABinternalDep)
+
 add_subdirectory(ExportLanguages)
diff --git a/Tests/PerConfig/perconfig.cmake b/Tests/PerConfig/perconfig.cmake
index 0731041..5286307 100644
--- a/Tests/PerConfig/perconfig.cmake
+++ b/Tests/PerConfig/perconfig.cmake
@@ -29,7 +29,7 @@
 
 # Verify that the implementation files are named correctly.
 foreach(lib pcStatic pcShared)
-  file(STRINGS "${${lib}_file}" info LIMIT_COUNT 1 REGEX "INFO:[^[]*\\[")
+  file(STRINGS "${${lib}_file}" info LIMIT_COUNT 1 REGEX "INFO:[A-Za-z0-9_]+\\[[^]]*\\]")
   if(NOT "${info}" MATCHES "INFO:symbol\\[${lib}\\]")
     message(SEND_ERROR "No INFO:symbol[${lib}] found in:\n  ${${lib}_file}")
   endif()
diff --git a/Tests/Preprocess/CMakeLists.txt b/Tests/Preprocess/CMakeLists.txt
index d44cb9c..cdfdcc1 100644
--- a/Tests/Preprocess/CMakeLists.txt
+++ b/Tests/Preprocess/CMakeLists.txt
@@ -34,15 +34,6 @@
 if("${CMAKE_GENERATOR}" MATCHES "Visual Studio")
   set(PP_VS 1)
 endif()
-if("${CMAKE_GENERATOR}" MATCHES "Visual Studio 10")
-  set(PP_VS100 1)
-endif()
-if("${CMAKE_GENERATOR}" MATCHES "Visual Studio 11")
-  set(PP_VS110 1)
-endif()
-if("${CMAKE_GENERATOR}" MATCHES "Visual Studio 12")
-  set(PP_VS120 1)
-endif()
 
 # Some tests below check the PP_* variables set above.  They are meant
 # to test the case that the build tool is at fault.  Other tests below
diff --git a/Tests/QtAutogen/CMakeLists.txt b/Tests/QtAutogen/CMakeLists.txt
index 3973653..3fd00b8 100644
--- a/Tests/QtAutogen/CMakeLists.txt
+++ b/Tests/QtAutogen/CMakeLists.txt
@@ -37,6 +37,9 @@
 
 endif()
 
+add_executable(rcconly rcconly.cpp second_resource.qrc)
+set_property(TARGET rcconly PROPERTY AUTORCC ON)
+target_link_libraries(rcconly ${QT_QTCORE_TARGET})
 
 include_directories(${CMAKE_CURRENT_BINARY_DIR})
 
@@ -71,6 +74,7 @@
 endif()
 
 add_executable(QtAutogen main.cpp calwidget.cpp second_widget.cpp foo.cpp blub.cpp bar.cpp abc.cpp
+               multiplewidgets.cpp
                xyz.cpp yaf.cpp gadget.cpp $<TARGET_OBJECTS:privateSlot>
                test.qrc second_resource.qrc resourcetester.cpp generated.cpp ${debug_srcs}
 )
diff --git a/Tests/QtAutogen/multiplewidgets.cpp b/Tests/QtAutogen/multiplewidgets.cpp
new file mode 100644
index 0000000..f143875
--- /dev/null
+++ b/Tests/QtAutogen/multiplewidgets.cpp
@@ -0,0 +1,19 @@
+
+#include "multiplewidgets.h"
+
+#include "ui_widget1.h"
+#include "ui_widget2.h"
+
+Widget1::Widget1(QWidget *parent)
+  : QWidget(parent),
+    ui(new Ui::Widget1)
+{
+  ui->setupUi(this);
+}
+
+Widget2::Widget2(QWidget *parent)
+  : QWidget(parent),
+    ui(new Ui::Widget2)
+{
+  ui->setupUi(this);
+}
diff --git a/Tests/QtAutogen/multiplewidgets.h b/Tests/QtAutogen/multiplewidgets.h
new file mode 100644
index 0000000..6ae6ad1
--- /dev/null
+++ b/Tests/QtAutogen/multiplewidgets.h
@@ -0,0 +1,33 @@
+
+#ifndef MULTIPLEWIDGETS_H
+#define MULTIPLEWIDGETS_H
+
+#include <QWidget>
+
+namespace Ui {
+class Widget1;
+}
+
+class Widget1 : public QWidget
+{
+  Q_OBJECT
+public:
+  Widget1(QWidget *parent = 0);
+private:
+  Ui::Widget1 *ui;
+};
+
+namespace Ui {
+class Widget2;
+}
+
+class Widget2 : public QWidget
+{
+  Q_OBJECT
+public:
+  Widget2(QWidget *parent = 0);
+private:
+  Ui::Widget2 *ui;
+};
+
+#endif
diff --git a/Tests/QtAutogen/rcconly.cpp b/Tests/QtAutogen/rcconly.cpp
new file mode 100644
index 0000000..854c4c1
--- /dev/null
+++ b/Tests/QtAutogen/rcconly.cpp
@@ -0,0 +1,9 @@
+
+extern int qInitResources_second_resource();
+
+int main(int, char**)
+{
+  // Fails to link if the symbol is not present.
+  qInitResources_second_resource();
+  return 0;
+}
diff --git a/Tests/QtAutogen/widget1.ui b/Tests/QtAutogen/widget1.ui
new file mode 100644
index 0000000..8fce81a
--- /dev/null
+++ b/Tests/QtAutogen/widget1.ui
@@ -0,0 +1,45 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>Widget1</class>
+ <widget class="QWidget" name="Widget1">
+  <property name="geometry">
+   <rect>
+    <x>0</x>
+    <y>0</y>
+    <width>400</width>
+    <height>300</height>
+   </rect>
+  </property>
+  <property name="windowTitle">
+   <string>Form</string>
+  </property>
+  <widget class="QPushButton" name="pushButton">
+   <property name="geometry">
+    <rect>
+     <x>140</x>
+     <y>80</y>
+     <width>80</width>
+     <height>23</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>PushButton</string>
+   </property>
+  </widget>
+  <widget class="QPushButton" name="pushButton_2">
+   <property name="geometry">
+    <rect>
+     <x>190</x>
+     <y>170</y>
+     <width>80</width>
+     <height>23</height>
+    </rect>
+   </property>
+   <property name="text">
+    <string>PushButton</string>
+   </property>
+  </widget>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>
diff --git a/Tests/QtAutogen/widget2.ui b/Tests/QtAutogen/widget2.ui
new file mode 100644
index 0000000..1f411b9
--- /dev/null
+++ b/Tests/QtAutogen/widget2.ui
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>Widget2</class>
+ <widget class="QWidget" name="Widget1">
+  <property name="geometry">
+   <rect>
+    <x>0</x>
+    <y>0</y>
+    <width>400</width>
+    <height>300</height>
+   </rect>
+  </property>
+  <property name="windowTitle">
+   <string>Form</string>
+  </property>
+  <widget class="QListWidget" name="listWidget">
+   <property name="geometry">
+    <rect>
+     <x>20</x>
+     <y>20</y>
+     <width>256</width>
+     <height>192</height>
+    </rect>
+   </property>
+  </widget>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>
diff --git a/Tests/RunCMake/CMP0054/CMP0054-NEW-stderr.txt b/Tests/RunCMake/CMP0054/CMP0054-NEW-stderr.txt
new file mode 100644
index 0000000..f5a8fbe
--- /dev/null
+++ b/Tests/RunCMake/CMP0054/CMP0054-NEW-stderr.txt
@@ -0,0 +1 @@
+$^
diff --git a/Tests/RunCMake/CMP0054/CMP0054-NEW.cmake b/Tests/RunCMake/CMP0054/CMP0054-NEW.cmake
new file mode 100644
index 0000000..23a9124
--- /dev/null
+++ b/Tests/RunCMake/CMP0054/CMP0054-NEW.cmake
@@ -0,0 +1,47 @@
+cmake_policy(SET CMP0054 NEW)
+
+set(FOO "BAR")
+set(BAZ "ZZZ")
+set(MYTRUE ON)
+set(MYNUMBER 3)
+set(MYVERSION 3.0)
+
+function(assert_unquoted PREFIX FIRST)
+  string(REPLACE ";" " " ARGN_SP "${ARGN}")
+  if(${PREFIX} ${FIRST} ${ARGN})
+    message(FATAL_ERROR "Assertion failed [${PREFIX} ${FIRST} ${ARGN_SP}]")
+  endif()
+endfunction()
+
+function(assert_quoted PREFIX FIRST)
+  string(REPLACE ";" " " ARGN_SP "${ARGN}")
+  if(${PREFIX} "${FIRST}" ${ARGN})
+    message(FATAL_ERROR "Assertion failed [${PREFIX} \"${FIRST}\" ${ARGN_SP}]")
+  endif()
+endfunction()
+
+function(assert FIRST)
+  assert_unquoted(NOT ${FIRST} ${ARGN})
+  assert_quoted("" ${FIRST} ${ARGN})
+endfunction()
+
+assert(MYTRUE)
+
+assert(FOO MATCHES "^BAR$")
+
+assert(MYNUMBER LESS 4)
+assert(MYNUMBER GREATER 2)
+assert(MYNUMBER EQUAL 3)
+
+assert(FOO STRLESS CCC)
+assert(BAZ STRGREATER CCC)
+assert(FOO STREQUAL BAR)
+
+assert_unquoted(NOT MYVERSION VERSION_LESS 3.1)
+assert_unquoted("" MYVERSION VERSION_LESS 2.9)
+
+assert_quoted(NOT MYVERSION VERSION_LESS 2.9)
+assert_quoted(NOT MYVERSION VERSION_LESS 3.1)
+
+assert(MYVERSION VERSION_GREATER 2.9)
+assert(MYVERSION VERSION_EQUAL 3.0)
diff --git a/Tests/RunCMake/CMP0054/CMP0054-OLD-stderr.txt b/Tests/RunCMake/CMP0054/CMP0054-OLD-stderr.txt
new file mode 100644
index 0000000..f5a8fbe
--- /dev/null
+++ b/Tests/RunCMake/CMP0054/CMP0054-OLD-stderr.txt
@@ -0,0 +1 @@
+$^
diff --git a/Tests/RunCMake/CMP0054/CMP0054-OLD.cmake b/Tests/RunCMake/CMP0054/CMP0054-OLD.cmake
new file mode 100644
index 0000000..0c4cede
--- /dev/null
+++ b/Tests/RunCMake/CMP0054/CMP0054-OLD.cmake
@@ -0,0 +1,47 @@
+cmake_policy(SET CMP0054 OLD)
+
+set(FOO "BAR")
+set(BAZ "ZZZ")
+set(MYTRUE ON)
+set(MYNUMBER 3)
+set(MYVERSION 3.0)
+
+function(assert_unquoted PREFIX FIRST)
+  string(REPLACE ";" " " ARGN_SP "${ARGN}")
+  if(${PREFIX} ${FIRST} ${ARGN})
+    message(FATAL_ERROR "Assertion failed [${PREFIX} ${FIRST} ${ARGN_SP}]")
+  endif()
+endfunction()
+
+function(assert_quoted PREFIX FIRST)
+  string(REPLACE ";" " " ARGN_SP "${ARGN}")
+  if(${PREFIX} "${FIRST}" ${ARGN})
+    message(FATAL_ERROR "Assertion failed [${PREFIX} \"${FIRST}\" ${ARGN_SP}]")
+  endif()
+endfunction()
+
+function(assert FIRST)
+  assert_unquoted(NOT ${FIRST} ${ARGN})
+  assert_quoted(NOT ${FIRST} ${ARGN})
+endfunction()
+
+assert(MYTRUE)
+
+assert(FOO MATCHES "^BAR$")
+
+assert(MYNUMBER LESS 4)
+assert(MYNUMBER GREATER 2)
+assert(MYNUMBER EQUAL 3)
+
+assert(FOO STRLESS CCC)
+assert(BAZ STRGREATER CCC)
+assert(FOO STREQUAL BAR)
+
+assert_unquoted(NOT MYVERSION VERSION_LESS 3.1)
+assert_unquoted("" MYVERSION VERSION_LESS 2.9)
+
+assert_quoted("" MYVERSION VERSION_LESS 2.9)
+assert_quoted(NOT MYVERSION VERSION_LESS 3.1)
+
+assert(MYVERSION VERSION_GREATER 2.9)
+assert(MYVERSION VERSION_EQUAL 3.0)
diff --git a/Tests/RunCMake/CMP0054/CMP0054-WARN-stderr.txt b/Tests/RunCMake/CMP0054/CMP0054-WARN-stderr.txt
new file mode 100644
index 0000000..3d875ae
--- /dev/null
+++ b/Tests/RunCMake/CMP0054/CMP0054-WARN-stderr.txt
@@ -0,0 +1,11 @@
+CMake Warning \(dev\) at CMP0054-WARN.cmake:3 \(if\):
+  Policy CMP0054 is not set: Only interpret if\(\) arguments as variables or
+  keywords when unquoted.  Run "cmake --help-policy CMP0054" for policy
+  details.  Use the cmake_policy command to set the policy and suppress this
+  warning.
+
+  Quoted variables like "FOO" will no longer be dereferenced when the policy
+  is set to NEW.  Since the policy is not set the OLD behavior will be used.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:3 \(include\)
+This warning is for project developers.  Use -Wno-dev to suppress it.
diff --git a/Tests/RunCMake/CMP0054/CMP0054-WARN.cmake b/Tests/RunCMake/CMP0054/CMP0054-WARN.cmake
new file mode 100644
index 0000000..37855fc
--- /dev/null
+++ b/Tests/RunCMake/CMP0054/CMP0054-WARN.cmake
@@ -0,0 +1,5 @@
+set(FOO "BAR")
+
+if(NOT "FOO" STREQUAL "BAR")
+  message(FATAL_ERROR "The given literals should match")
+endif()
diff --git a/Tests/RunCMake/CMP0054/CMP0054-duplicate-warnings-stderr.txt b/Tests/RunCMake/CMP0054/CMP0054-duplicate-warnings-stderr.txt
new file mode 100644
index 0000000..485db52
--- /dev/null
+++ b/Tests/RunCMake/CMP0054/CMP0054-duplicate-warnings-stderr.txt
@@ -0,0 +1,24 @@
+CMake Warning \(dev\) at CMP0054-duplicate-warnings.cmake:4 \(if\):
+  Policy CMP0054 is not set: Only interpret if\(\) arguments as variables or
+  keywords when unquoted.  Run "cmake --help-policy CMP0054" for policy
+  details.  Use the cmake_policy command to set the policy and suppress this
+  warning.
+
+  Quoted variables like "FOO" will no longer be dereferenced when the policy
+  is set to NEW.  Since the policy is not set the OLD behavior will be used.
+Call Stack \(most recent call first\):
+  CMP0054-duplicate-warnings.cmake:8 \(generate_warning\)
+  CMakeLists.txt:3 \(include\)
+This warning is for project developers.  Use -Wno-dev to suppress it.
+
+CMake Warning \(dev\) at CMP0054-duplicate-warnings.cmake:11 \(if\):
+  Policy CMP0054 is not set: Only interpret if\(\) arguments as variables or
+  keywords when unquoted.  Run "cmake --help-policy CMP0054" for policy
+  details.  Use the cmake_policy command to set the policy and suppress this
+  warning.
+
+  Quoted variables like "FOO" will no longer be dereferenced when the policy
+  is set to NEW.  Since the policy is not set the OLD behavior will be used.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:3 \(include\)
+This warning is for project developers.  Use -Wno-dev to suppress it.
diff --git a/Tests/RunCMake/CMP0054/CMP0054-duplicate-warnings.cmake b/Tests/RunCMake/CMP0054/CMP0054-duplicate-warnings.cmake
new file mode 100644
index 0000000..04fbe14
--- /dev/null
+++ b/Tests/RunCMake/CMP0054/CMP0054-duplicate-warnings.cmake
@@ -0,0 +1,12 @@
+set(FOO "BAR")
+
+function(generate_warning)
+  if("FOO" STREQUAL "BAR")
+  endif()
+endfunction()
+
+generate_warning()
+generate_warning()
+
+if("FOO" STREQUAL "BAR")
+endif()
diff --git a/Tests/RunCMake/CMP0054/CMP0054-keywords-NEW-result.txt b/Tests/RunCMake/CMP0054/CMP0054-keywords-NEW-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/CMP0054/CMP0054-keywords-NEW-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CMP0054/CMP0054-keywords-NEW-stderr.txt b/Tests/RunCMake/CMP0054/CMP0054-keywords-NEW-stderr.txt
new file mode 100644
index 0000000..f444684
--- /dev/null
+++ b/Tests/RunCMake/CMP0054/CMP0054-keywords-NEW-stderr.txt
@@ -0,0 +1,8 @@
+CMake Error at CMP0054-keywords-NEW.cmake:23 \(if\):
+  if given arguments:
+
+    "NOT" "1"
+
+  Unknown arguments specified
+Call Stack \(most recent call first\):
+  CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/CMP0054/CMP0054-keywords-NEW.cmake b/Tests/RunCMake/CMP0054/CMP0054-keywords-NEW.cmake
new file mode 100644
index 0000000..b957658
--- /dev/null
+++ b/Tests/RunCMake/CMP0054/CMP0054-keywords-NEW.cmake
@@ -0,0 +1,25 @@
+cmake_policy(SET CMP0054 NEW)
+
+function(assert KEYWORD)
+  if("${KEYWORD}" STREQUAL "${KEYWORD}")
+  else()
+    message(FATAL_ERROR
+      "Assertion failed [\"${KEYWORD}\" STREQUAL \"${KEYWORD}\"]")
+  endif()
+endfunction()
+
+assert("NOT")
+assert("COMMAND")
+assert("POLICY")
+assert("TARGET")
+assert("EXISTS")
+assert("IS_DIRECTORY")
+assert("IS_SYMLINK")
+assert("IS_ABSOLUTE")
+assert("DEFINED")
+assert("(")
+assert(")")
+
+if("NOT" 1)
+  message(FATAL_ERROR "[\"NOT\" 1] evaluated true")
+endif()
diff --git a/Tests/RunCMake/CMP0054/CMP0054-keywords-OLD-stderr.txt b/Tests/RunCMake/CMP0054/CMP0054-keywords-OLD-stderr.txt
new file mode 100644
index 0000000..f5a8fbe
--- /dev/null
+++ b/Tests/RunCMake/CMP0054/CMP0054-keywords-OLD-stderr.txt
@@ -0,0 +1 @@
+$^
diff --git a/Tests/RunCMake/CMP0054/CMP0054-keywords-OLD.cmake b/Tests/RunCMake/CMP0054/CMP0054-keywords-OLD.cmake
new file mode 100644
index 0000000..a2a7f51
--- /dev/null
+++ b/Tests/RunCMake/CMP0054/CMP0054-keywords-OLD.cmake
@@ -0,0 +1,9 @@
+cmake_policy(SET CMP0054 OLD)
+
+if(NOT 1)
+  message(FATAL_ERROR "[NOT 1] evaluated true")
+endif()
+
+if("NOT" 1)
+  message(FATAL_ERROR "[\"NOT\" 1] evaluated true")
+endif()
diff --git a/Tests/RunCMake/CMP0054/CMP0054-keywords-WARN-stderr.txt b/Tests/RunCMake/CMP0054/CMP0054-keywords-WARN-stderr.txt
new file mode 100644
index 0000000..b1ebd49
--- /dev/null
+++ b/Tests/RunCMake/CMP0054/CMP0054-keywords-WARN-stderr.txt
@@ -0,0 +1,12 @@
+CMake Warning \(dev\) at CMP0054-keywords-WARN.cmake:1 \(if\):
+  Policy CMP0054 is not set: Only interpret if\(\) arguments as variables or
+  keywords when unquoted.  Run "cmake --help-policy CMP0054" for policy
+  details.  Use the cmake_policy command to set the policy and suppress this
+  warning.
+
+  Quoted keywords like "NOT" will no longer be interpreted as keywords when
+  the policy is set to NEW.  Since the policy is not set the OLD behavior
+  will be used.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:3 \(include\)
+This warning is for project developers.  Use -Wno-dev to suppress it.
diff --git a/Tests/RunCMake/CMP0054/CMP0054-keywords-WARN.cmake b/Tests/RunCMake/CMP0054/CMP0054-keywords-WARN.cmake
new file mode 100644
index 0000000..ee0a623
--- /dev/null
+++ b/Tests/RunCMake/CMP0054/CMP0054-keywords-WARN.cmake
@@ -0,0 +1,3 @@
+if("NOT" 1)
+  message(FATAL_ERROR "[\"NOT\" 1] evaluated true")
+endif()
diff --git a/Tests/RunCMake/CMP0054/CMP0054-policy-command-scope-stderr.txt b/Tests/RunCMake/CMP0054/CMP0054-policy-command-scope-stderr.txt
new file mode 100644
index 0000000..f5a8fbe
--- /dev/null
+++ b/Tests/RunCMake/CMP0054/CMP0054-policy-command-scope-stderr.txt
@@ -0,0 +1 @@
+$^
diff --git a/Tests/RunCMake/CMP0054/CMP0054-policy-command-scope.cmake b/Tests/RunCMake/CMP0054/CMP0054-policy-command-scope.cmake
new file mode 100644
index 0000000..b6b243c
--- /dev/null
+++ b/Tests/RunCMake/CMP0054/CMP0054-policy-command-scope.cmake
@@ -0,0 +1,53 @@
+set(FOO BAR)
+
+cmake_policy(SET CMP0054 NEW)
+
+function(function_defined_new_called_old)
+  if(NOT FOO STREQUAL BAR)
+    message(FATAL_ERROR "The variable should match the string")
+  endif()
+
+  if("FOO" STREQUAL BAR)
+    message(FATAL_ERROR "The strings should not match")
+  endif()
+endfunction()
+
+macro(macro_defined_new_called_old)
+  if(NOT FOO STREQUAL BAR)
+    message(FATAL_ERROR "The variable should match the string")
+  endif()
+
+  if("FOO" STREQUAL BAR)
+    message(FATAL_ERROR "The strings should not match")
+  endif()
+endmacro()
+
+cmake_policy(SET CMP0054 OLD)
+
+function_defined_new_called_old()
+macro_defined_new_called_old()
+
+function(function_defined_old_called_new)
+  if(NOT FOO STREQUAL BAR)
+    message(FATAL_ERROR "The variable should match the string")
+  endif()
+
+  if(NOT "FOO" STREQUAL BAR)
+    message(FATAL_ERROR "The quoted variable should match the string")
+  endif()
+endfunction()
+
+macro(macro_defined_old_called_new)
+  if(NOT FOO STREQUAL BAR)
+    message(FATAL_ERROR "The variable should match the string")
+  endif()
+
+  if(NOT "FOO" STREQUAL BAR)
+    message(FATAL_ERROR "The quoted variable should match the string")
+  endif()
+endmacro()
+
+cmake_policy(SET CMP0054 NEW)
+
+function_defined_old_called_new()
+macro_defined_old_called_new()
diff --git a/Tests/RunCMake/CMP0054/CMP0054-policy-foreach-scope-stderr.txt b/Tests/RunCMake/CMP0054/CMP0054-policy-foreach-scope-stderr.txt
new file mode 100644
index 0000000..f5a8fbe
--- /dev/null
+++ b/Tests/RunCMake/CMP0054/CMP0054-policy-foreach-scope-stderr.txt
@@ -0,0 +1 @@
+$^
diff --git a/Tests/RunCMake/CMP0054/CMP0054-policy-foreach-scope.cmake b/Tests/RunCMake/CMP0054/CMP0054-policy-foreach-scope.cmake
new file mode 100644
index 0000000..87c968a
--- /dev/null
+++ b/Tests/RunCMake/CMP0054/CMP0054-policy-foreach-scope.cmake
@@ -0,0 +1,49 @@
+set(FOO BAR)
+
+cmake_policy(SET CMP0054 NEW)
+
+foreach(loop_var arg1 arg2)
+  if(NOT FOO STREQUAL BAR)
+    message(FATAL_ERROR "The variable should match the string")
+  endif()
+
+  if("FOO" STREQUAL BAR)
+    message(FATAL_ERROR "The strings should not match")
+  endif()
+
+  cmake_policy(SET CMP0054 OLD)
+
+  if(NOT FOO STREQUAL BAR)
+    message(FATAL_ERROR "The variable should match the string")
+  endif()
+
+  if(NOT "FOO" STREQUAL BAR)
+    message(FATAL_ERROR "The quoted variable should match the string")
+  endif()
+
+  cmake_policy(SET CMP0054 NEW)
+endforeach()
+
+cmake_policy(SET CMP0054 OLD)
+
+foreach(loop_var arg1 arg2)
+  if(NOT FOO STREQUAL BAR)
+    message(FATAL_ERROR "The variable should match the string")
+  endif()
+
+  if(NOT "FOO" STREQUAL BAR)
+    message(FATAL_ERROR "The quoted variable should match the string")
+  endif()
+
+  cmake_policy(SET CMP0054 NEW)
+
+  if(NOT FOO STREQUAL BAR)
+    message(FATAL_ERROR "The variable should match the string")
+  endif()
+
+  if("FOO" STREQUAL BAR)
+    message(FATAL_ERROR "The strings should not match")
+  endif()
+
+  cmake_policy(SET CMP0054 OLD)
+endforeach()
diff --git a/Tests/RunCMake/CMP0054/CMP0054-policy-nested-if-stderr.txt b/Tests/RunCMake/CMP0054/CMP0054-policy-nested-if-stderr.txt
new file mode 100644
index 0000000..f5a8fbe
--- /dev/null
+++ b/Tests/RunCMake/CMP0054/CMP0054-policy-nested-if-stderr.txt
@@ -0,0 +1 @@
+$^
diff --git a/Tests/RunCMake/CMP0054/CMP0054-policy-nested-if.cmake b/Tests/RunCMake/CMP0054/CMP0054-policy-nested-if.cmake
new file mode 100644
index 0000000..dd7434d
--- /dev/null
+++ b/Tests/RunCMake/CMP0054/CMP0054-policy-nested-if.cmake
@@ -0,0 +1,41 @@
+set(FOO BAR)
+
+cmake_policy(SET CMP0054 NEW)
+
+if("FOO" STREQUAL BAR)
+  message(FATAL_ERROR "The strings should not match")
+
+  if("FOO" STREQUAL BAR)
+    message(FATAL_ERROR "The strings should not match")
+  endif()
+
+  cmake_policy(SET CMP0054 OLD)
+
+  if(NOT "FOO" STREQUAL BAR)
+    message(FATAL_ERROR "The quoted variable should match the string")
+  endif()
+endif()
+
+if("FOO" STREQUAL BAR)
+  message(FATAL_ERROR "The strings should not match")
+endif()
+
+cmake_policy(SET CMP0054 OLD)
+
+if(NOT "FOO" STREQUAL BAR)
+  message(FATAL_ERROR "The quoted variable should match the string")
+
+  if(NOT "FOO" STREQUAL BAR)
+    message(FATAL_ERROR "The quoted variable should match the string")
+  endif()
+
+  cmake_policy(SET CMP0054 NEW)
+
+  if("FOO" STREQUAL BAR)
+    message(FATAL_ERROR "The strings should not match")
+  endif()
+endif()
+
+if(NOT "FOO" STREQUAL BAR)
+  message(FATAL_ERROR "The quoted variable should match the string")
+endif()
diff --git a/Tests/RunCMake/CMP0054/CMP0054-policy-while-scope-stderr.txt b/Tests/RunCMake/CMP0054/CMP0054-policy-while-scope-stderr.txt
new file mode 100644
index 0000000..f5a8fbe
--- /dev/null
+++ b/Tests/RunCMake/CMP0054/CMP0054-policy-while-scope-stderr.txt
@@ -0,0 +1 @@
+$^
diff --git a/Tests/RunCMake/CMP0054/CMP0054-policy-while-scope.cmake b/Tests/RunCMake/CMP0054/CMP0054-policy-while-scope.cmake
new file mode 100644
index 0000000..2b22778
--- /dev/null
+++ b/Tests/RunCMake/CMP0054/CMP0054-policy-while-scope.cmake
@@ -0,0 +1,65 @@
+set(FOO BAR)
+
+set(LOOP_VAR "")
+
+cmake_policy(SET CMP0054 NEW)
+
+while(NOT LOOP_VAR STREQUAL "xx")
+  if(NOT FOO STREQUAL BAR)
+    message(FATAL_ERROR "The variable should match the string")
+  endif()
+
+  if("FOO" STREQUAL BAR)
+    message(FATAL_ERROR "The strings should not match")
+  endif()
+
+  cmake_policy(SET CMP0054 OLD)
+
+  if(NOT FOO STREQUAL BAR)
+    message(FATAL_ERROR "The variable should match the string")
+  endif()
+
+  if(NOT "FOO" STREQUAL BAR)
+    message(FATAL_ERROR "The quoted variable should match the string")
+  endif()
+
+  cmake_policy(SET CMP0054 NEW)
+
+  set(LOOP_VAR "${LOOP_VAR}x")
+endwhile()
+
+while("FOO" STREQUAL BAR)
+  message(FATAL_ERROR "The strings should not match")
+endwhile()
+
+set(LOOP_VAR "")
+
+cmake_policy(SET CMP0054 OLD)
+
+while(NOT LOOP_VAR STREQUAL "xx")
+  if(NOT FOO STREQUAL BAR)
+    message(FATAL_ERROR "The variable should match the string")
+  endif()
+
+  if(NOT "FOO" STREQUAL BAR)
+    message(FATAL_ERROR "The quoted variable should match the string")
+  endif()
+
+  cmake_policy(SET CMP0054 NEW)
+
+  if(NOT FOO STREQUAL BAR)
+    message(FATAL_ERROR "The variable should match the string")
+  endif()
+
+  if("FOO" STREQUAL BAR)
+    message(FATAL_ERROR "The strings should not match")
+  endif()
+
+  cmake_policy(SET CMP0054 OLD)
+
+  set(LOOP_VAR "${LOOP_VAR}x")
+endwhile()
+
+if(NOT "FOO" STREQUAL BAR)
+  message(FATAL_ERROR "The quoted variable should match the string")
+endif()
diff --git a/Tests/RunCMake/CMP0054/CMakeLists.txt b/Tests/RunCMake/CMP0054/CMakeLists.txt
new file mode 100644
index 0000000..2897109
--- /dev/null
+++ b/Tests/RunCMake/CMP0054/CMakeLists.txt
@@ -0,0 +1,3 @@
+cmake_minimum_required(VERSION 3.0)
+project(${RunCMake_TEST} NONE)
+include(${RunCMake_TEST}.cmake)
diff --git a/Tests/RunCMake/CMP0054/RunCMakeTest.cmake b/Tests/RunCMake/CMP0054/RunCMakeTest.cmake
new file mode 100644
index 0000000..2f2fb76
--- /dev/null
+++ b/Tests/RunCMake/CMP0054/RunCMakeTest.cmake
@@ -0,0 +1,13 @@
+include(RunCMake)
+
+run_cmake(CMP0054-OLD)
+run_cmake(CMP0054-NEW)
+run_cmake(CMP0054-WARN)
+run_cmake(CMP0054-keywords-NEW)
+run_cmake(CMP0054-keywords-OLD)
+run_cmake(CMP0054-keywords-WARN)
+run_cmake(CMP0054-duplicate-warnings)
+run_cmake(CMP0054-policy-command-scope)
+run_cmake(CMP0054-policy-foreach-scope)
+run_cmake(CMP0054-policy-while-scope)
+run_cmake(CMP0054-policy-nested-if)
diff --git a/Tests/RunCMake/CMakeLists.txt b/Tests/RunCMake/CMakeLists.txt
index 06272ce..fd3bb03 100644
--- a/Tests/RunCMake/CMakeLists.txt
+++ b/Tests/RunCMake/CMakeLists.txt
@@ -4,6 +4,7 @@
   add_test(RunCMake.${test} ${CMAKE_CMAKE_COMMAND}
     -DCMAKE_MODULE_PATH=${CMAKE_CURRENT_SOURCE_DIR}
     -DRunCMake_GENERATOR=${CMAKE_GENERATOR}
+    -DRunCMake_GENERATOR_PLATFORM=${CMAKE_GENERATOR_PLATFORM}
     -DRunCMake_GENERATOR_TOOLSET=${CMAKE_GENERATOR_TOOLSET}
     -DRunCMake_SOURCE_DIR=${CMAKE_CURRENT_SOURCE_DIR}/${test}
     -DRunCMake_BINARY_DIR=${CMAKE_CURRENT_BINARY_DIR}/${test}
@@ -18,6 +19,13 @@
 
 if(XCODE_VERSION AND "${XCODE_VERSION}" VERSION_LESS 2)
   set(TargetSources_ARGS -DXCODE_BELOW_2=1)
+  set(File_Generate_ARGS -DXCODE_BELOW_2=1)
+endif()
+
+# Test MSVC for older host CMake versions, and test
+# WIN32/CMAKE_C_COMPILER_ID to fix check on Intel for Windows.
+if(MSVC OR (WIN32 AND CMAKE_C_COMPILER_ID MATCHES "MSVC|Intel"))
+  set(GeneratorExpression_ARGS -DLINKER_SUPPORTS_PDB=1)
 endif()
 
 add_RunCMake_test(CMP0019)
@@ -40,8 +48,9 @@
 add_RunCMake_test(CMP0050)
 add_RunCMake_test(CMP0051)
 add_RunCMake_test(CMP0053)
+add_RunCMake_test(CMP0054)
 add_RunCMake_test(CTest)
-if(UNIX AND "${CMAKE_GENERATOR}" MATCHES "Unix Makefiles")
+if(UNIX AND "${CMAKE_GENERATOR}" MATCHES "Unix Makefiles|Ninja")
   add_RunCMake_test(CompilerChange)
 endif()
 add_RunCMake_test(CompilerNotFound)
@@ -51,6 +60,7 @@
 add_RunCMake_test(FeatureSummary)
 add_RunCMake_test(FPHSA)
 add_RunCMake_test(GeneratorExpression)
+add_RunCMake_test(GeneratorPlatform)
 add_RunCMake_test(GeneratorToolset)
 add_RunCMake_test(TargetPropertyGeneratorExpressions)
 add_RunCMake_test(Languages)
diff --git a/Tests/RunCMake/CommandLine/E_env-bad-arg1-result.txt b/Tests/RunCMake/CommandLine/E_env-bad-arg1-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_env-bad-arg1-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/E_env-bad-arg1-stderr.txt b/Tests/RunCMake/CommandLine/E_env-bad-arg1-stderr.txt
new file mode 100644
index 0000000..2143ba4
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_env-bad-arg1-stderr.txt
@@ -0,0 +1 @@
+^cmake -E env: unknown option '-bad-arg1'$
diff --git a/Tests/RunCMake/CommandLine/E_env-no-command0-result.txt b/Tests/RunCMake/CommandLine/E_env-no-command0-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_env-no-command0-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/E_env-no-command0-stderr.txt b/Tests/RunCMake/CommandLine/E_env-no-command0-stderr.txt
new file mode 100644
index 0000000..d2efa53
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_env-no-command0-stderr.txt
@@ -0,0 +1 @@
+^cmake -E env: no command given$
diff --git a/Tests/RunCMake/CommandLine/E_env-no-command1-result.txt b/Tests/RunCMake/CommandLine/E_env-no-command1-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_env-no-command1-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/E_env-no-command1-stderr.txt b/Tests/RunCMake/CommandLine/E_env-no-command1-stderr.txt
new file mode 100644
index 0000000..d2efa53
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_env-no-command1-stderr.txt
@@ -0,0 +1 @@
+^cmake -E env: no command given$
diff --git a/Tests/RunCMake/CommandLine/E_env-set-stdout.txt b/Tests/RunCMake/CommandLine/E_env-set-stdout.txt
new file mode 100644
index 0000000..feff117
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_env-set-stdout.txt
@@ -0,0 +1 @@
+^-- TEST_ENV is correctly set in environment: 1$
diff --git a/Tests/RunCMake/CommandLine/E_env-set.cmake b/Tests/RunCMake/CommandLine/E_env-set.cmake
new file mode 100644
index 0000000..c2639b6
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_env-set.cmake
@@ -0,0 +1,5 @@
+if(DEFINED ENV{TEST_ENV})
+  message(STATUS "TEST_ENV is correctly set in environment: $ENV{TEST_ENV}")
+else()
+  message(FATAL_ERROR "TEST_ENV is incorrectly not set in environment")
+endif()
diff --git a/Tests/RunCMake/CommandLine/E_env-unset-stdout.txt b/Tests/RunCMake/CommandLine/E_env-unset-stdout.txt
new file mode 100644
index 0000000..a1d5c01
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_env-unset-stdout.txt
@@ -0,0 +1 @@
+^-- TEST_ENV is correctly not set in environment$
diff --git a/Tests/RunCMake/CommandLine/E_env-unset.cmake b/Tests/RunCMake/CommandLine/E_env-unset.cmake
new file mode 100644
index 0000000..04976fb
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_env-unset.cmake
@@ -0,0 +1,5 @@
+if(DEFINED ENV{TEST_ENV})
+  message(FATAL_ERROR "TEST_ENV is incorrectly set in environment")
+else()
+  message(STATUS "TEST_ENV is correctly not set in environment")
+endif()
diff --git a/Tests/RunCMake/CommandLine/P_directory-result.txt b/Tests/RunCMake/CommandLine/P_directory-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/P_directory-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/P_directory-stderr.txt b/Tests/RunCMake/CommandLine/P_directory-stderr.txt
new file mode 100644
index 0000000..b8319a1
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/P_directory-stderr.txt
@@ -0,0 +1 @@
+^CMake Error: Error processing file: .*/Tests/RunCMake/CommandLine$
diff --git a/Tests/RunCMake/CommandLine/RunCMakeTest.cmake b/Tests/RunCMake/CommandLine/RunCMakeTest.cmake
index 3aaeac0..5622a5b 100644
--- a/Tests/RunCMake/CommandLine/RunCMakeTest.cmake
+++ b/Tests/RunCMake/CommandLine/RunCMakeTest.cmake
@@ -31,7 +31,15 @@
     )
 endif()
 
+run_cmake_command(E_env-no-command0 ${CMAKE_COMMAND} -E env)
+run_cmake_command(E_env-no-command1 ${CMAKE_COMMAND} -E env TEST_ENV=1)
+run_cmake_command(E_env-bad-arg1 ${CMAKE_COMMAND} -E env -bad-arg1)
+run_cmake_command(E_env-set   ${CMAKE_COMMAND} -E env TEST_ENV=1 ${CMAKE_COMMAND} -P ${RunCMake_SOURCE_DIR}/E_env-set.cmake)
+run_cmake_command(E_env-unset ${CMAKE_COMMAND} -E env TEST_ENV=1 ${CMAKE_COMMAND} -E env --unset=TEST_ENV ${CMAKE_COMMAND} -P ${RunCMake_SOURCE_DIR}/E_env-unset.cmake)
+
 run_cmake_command(E_sleep-no-args ${CMAKE_COMMAND} -E sleep)
 run_cmake_command(E_sleep-bad-arg1 ${CMAKE_COMMAND} -E sleep x)
 run_cmake_command(E_sleep-bad-arg2 ${CMAKE_COMMAND} -E sleep 1 -1)
 run_cmake_command(E_sleep-one-tenth ${CMAKE_COMMAND} -E sleep 0.1)
+
+run_cmake_command(P_directory ${CMAKE_COMMAND} -P ${RunCMake_SOURCE_DIR})
diff --git a/Tests/RunCMake/CompatibleInterface/DebugProperties-stderr.txt b/Tests/RunCMake/CompatibleInterface/DebugProperties-stderr.txt
index 82a34d5..17b8a5c 100644
--- a/Tests/RunCMake/CompatibleInterface/DebugProperties-stderr.txt
+++ b/Tests/RunCMake/CompatibleInterface/DebugProperties-stderr.txt
@@ -1,11 +1,4 @@
 CMake Debug Log:
-  Boolean compatibility of property "BOOL_PROP7" for target
-  "CompatibleInterface" \(result: "FALSE"\):
-
-   \* Target "CompatibleInterface" property is implied by use.
-   \* Target "iface1" property value "FALSE" \(Agree\)
-+
-CMake Debug Log:
   Boolean compatibility of property "BOOL_PROP1" for target
   "CompatibleInterface" \(result: "TRUE"\):
 
@@ -47,6 +40,13 @@
    \* Target "iface2" property value "FALSE" \(Agree\)
 +
 CMake Debug Log:
+  Boolean compatibility of property "BOOL_PROP7" for target
+  "CompatibleInterface" \(result: "FALSE"\):
+
+   \* Target "CompatibleInterface" property is implied by use.
+   \* Target "iface1" property value "FALSE" \(Agree\)
++
+CMake Debug Log:
   String compatibility of property "STRING_PROP1" for target
   "CompatibleInterface" \(result: "prop1"\):
 
diff --git a/Tests/RunCMake/Configure/CustomTargetAfterError-result.txt b/Tests/RunCMake/Configure/CustomTargetAfterError-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/Configure/CustomTargetAfterError-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/Configure/CustomTargetAfterError-stderr.txt b/Tests/RunCMake/Configure/CustomTargetAfterError-stderr.txt
new file mode 100644
index 0000000..7ce7daf
--- /dev/null
+++ b/Tests/RunCMake/Configure/CustomTargetAfterError-stderr.txt
@@ -0,0 +1,9 @@
+^CMake Error at CustomTargetAfterError.cmake:1 \(message\):
+  Error before add_custom_target
+Call Stack \(most recent call first\):
+  CMakeLists.txt:3 \(include\)
++
+CMake Error at CustomTargetAfterError.cmake:3 \(message\):
+  Error after add_custom_target
+Call Stack \(most recent call first\):
+  CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/Configure/CustomTargetAfterError.cmake b/Tests/RunCMake/Configure/CustomTargetAfterError.cmake
new file mode 100644
index 0000000..3e26455
--- /dev/null
+++ b/Tests/RunCMake/Configure/CustomTargetAfterError.cmake
@@ -0,0 +1,3 @@
+message(SEND_ERROR "Error before add_custom_target")
+add_custom_target(foo COMMAND echo)
+message(SEND_ERROR "Error after add_custom_target")
diff --git a/Tests/RunCMake/Configure/RunCMakeTest.cmake b/Tests/RunCMake/Configure/RunCMakeTest.cmake
index 5ef0384..58e1a2a 100644
--- a/Tests/RunCMake/Configure/RunCMakeTest.cmake
+++ b/Tests/RunCMake/Configure/RunCMakeTest.cmake
@@ -1,5 +1,6 @@
 include(RunCMake)
 
+run_cmake(CustomTargetAfterError)
 run_cmake(ErrorLogs)
 run_cmake(FailCopyFileABI)
 
diff --git a/Tests/RunCMake/FPHSA/FindPseudo.cmake b/Tests/RunCMake/FPHSA/FindPseudo.cmake
new file mode 100644
index 0000000..dc3558b
--- /dev/null
+++ b/Tests/RunCMake/FPHSA/FindPseudo.cmake
@@ -0,0 +1,6 @@
+# pseudo find_module
+
+set(FOOBAR TRUE)
+
+include(FindPackageHandleStandardArgs)
+find_package_handle_standard_args(Pseudo REQUIRED_VARS FOOBAR VERSION_VAR Pseudo_VERSION)
diff --git a/Tests/RunCMake/FPHSA/RunCMakeTest.cmake b/Tests/RunCMake/FPHSA/RunCMakeTest.cmake
index 0d48fa9..bb7743c 100644
--- a/Tests/RunCMake/FPHSA/RunCMakeTest.cmake
+++ b/Tests/RunCMake/FPHSA/RunCMakeTest.cmake
@@ -1,3 +1,28 @@
 include(RunCMake)
 
 run_cmake(BadFoundVar)
+
+# The pseudo module will "find" a package with the given version. Check if the
+# version selection code in FPHSA works correctly.
+set(RunCMake_TEST_OPTIONS "-DCMAKE_MODULE_PATH=${CMAKE_CURRENT_LIST_DIR}" "-DPseudo_VERSION=1.2.3.4.5")
+run_cmake(any_version)
+
+# test EXACT mode with every subcomponent
+run_cmake(exact_1)
+run_cmake(exact_1.2)
+run_cmake(exact_1.2.3)
+run_cmake(exact_1.2.3.4)
+
+# now test every component with an invalid version
+run_cmake(exact_0)
+run_cmake(exact_2)
+run_cmake(exact_1.1)
+run_cmake(exact_1.3)
+run_cmake(exact_1.2.2)
+run_cmake(exact_1.2.4)
+run_cmake(exact_1.2.3.3)
+run_cmake(exact_1.2.3.5)
+
+# check if searching for a version 0 works
+list(APPEND RunCMake_TEST_OPTIONS "-DCMAKE_MODULE_PATH=${CMAKE_CURRENT_LIST_DIR}" "-DPseudo_VERSION=0")
+run_cmake(exact_0_matching)
diff --git a/Tests/RunCMake/FPHSA/any_version.cmake b/Tests/RunCMake/FPHSA/any_version.cmake
new file mode 100644
index 0000000..b34a540
--- /dev/null
+++ b/Tests/RunCMake/FPHSA/any_version.cmake
@@ -0,0 +1 @@
+find_package(Pseudo REQUIRED)
diff --git a/Tests/RunCMake/FPHSA/exact_0-result.txt b/Tests/RunCMake/FPHSA/exact_0-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/FPHSA/exact_0-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/FPHSA/exact_0.cmake b/Tests/RunCMake/FPHSA/exact_0.cmake
new file mode 100644
index 0000000..432887b
--- /dev/null
+++ b/Tests/RunCMake/FPHSA/exact_0.cmake
@@ -0,0 +1 @@
+find_package(Pseudo 0 EXACT REQUIRED)
diff --git a/Tests/RunCMake/FPHSA/exact_0_matching.cmake b/Tests/RunCMake/FPHSA/exact_0_matching.cmake
new file mode 100644
index 0000000..432887b
--- /dev/null
+++ b/Tests/RunCMake/FPHSA/exact_0_matching.cmake
@@ -0,0 +1 @@
+find_package(Pseudo 0 EXACT REQUIRED)
diff --git a/Tests/RunCMake/FPHSA/exact_1.1-result.txt b/Tests/RunCMake/FPHSA/exact_1.1-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/FPHSA/exact_1.1-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/FPHSA/exact_1.1.cmake b/Tests/RunCMake/FPHSA/exact_1.1.cmake
new file mode 100644
index 0000000..d967da9
--- /dev/null
+++ b/Tests/RunCMake/FPHSA/exact_1.1.cmake
@@ -0,0 +1 @@
+find_package(Pseudo 1.1 EXACT REQUIRED)
diff --git a/Tests/RunCMake/FPHSA/exact_1.2.2-result.txt b/Tests/RunCMake/FPHSA/exact_1.2.2-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/FPHSA/exact_1.2.2-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/FPHSA/exact_1.2.2.cmake b/Tests/RunCMake/FPHSA/exact_1.2.2.cmake
new file mode 100644
index 0000000..e959f61
--- /dev/null
+++ b/Tests/RunCMake/FPHSA/exact_1.2.2.cmake
@@ -0,0 +1 @@
+find_package(Pseudo 1.2.2 EXACT REQUIRED)
diff --git a/Tests/RunCMake/FPHSA/exact_1.2.3.3-result.txt b/Tests/RunCMake/FPHSA/exact_1.2.3.3-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/FPHSA/exact_1.2.3.3-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/FPHSA/exact_1.2.3.3.cmake b/Tests/RunCMake/FPHSA/exact_1.2.3.3.cmake
new file mode 100644
index 0000000..af53cc8
--- /dev/null
+++ b/Tests/RunCMake/FPHSA/exact_1.2.3.3.cmake
@@ -0,0 +1 @@
+find_package(Pseudo 1.2.3.3 EXACT REQUIRED)
diff --git a/Tests/RunCMake/FPHSA/exact_1.2.3.4.cmake b/Tests/RunCMake/FPHSA/exact_1.2.3.4.cmake
new file mode 100644
index 0000000..1e2baa6
--- /dev/null
+++ b/Tests/RunCMake/FPHSA/exact_1.2.3.4.cmake
@@ -0,0 +1 @@
+find_package(Pseudo 1.2.3.4 EXACT REQUIRED)
diff --git a/Tests/RunCMake/FPHSA/exact_1.2.3.5-result.txt b/Tests/RunCMake/FPHSA/exact_1.2.3.5-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/FPHSA/exact_1.2.3.5-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/FPHSA/exact_1.2.3.5.cmake b/Tests/RunCMake/FPHSA/exact_1.2.3.5.cmake
new file mode 100644
index 0000000..ddb0d13
--- /dev/null
+++ b/Tests/RunCMake/FPHSA/exact_1.2.3.5.cmake
@@ -0,0 +1 @@
+find_package(Pseudo 1.2.3.5 EXACT REQUIRED)
diff --git a/Tests/RunCMake/FPHSA/exact_1.2.3.cmake b/Tests/RunCMake/FPHSA/exact_1.2.3.cmake
new file mode 100644
index 0000000..bf9b2a3
--- /dev/null
+++ b/Tests/RunCMake/FPHSA/exact_1.2.3.cmake
@@ -0,0 +1 @@
+find_package(Pseudo 1.2.3 EXACT REQUIRED)
diff --git a/Tests/RunCMake/FPHSA/exact_1.2.4-result.txt b/Tests/RunCMake/FPHSA/exact_1.2.4-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/FPHSA/exact_1.2.4-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/FPHSA/exact_1.2.4.cmake b/Tests/RunCMake/FPHSA/exact_1.2.4.cmake
new file mode 100644
index 0000000..548a079
--- /dev/null
+++ b/Tests/RunCMake/FPHSA/exact_1.2.4.cmake
@@ -0,0 +1 @@
+find_package(Pseudo 1.2.4 EXACT REQUIRED)
diff --git a/Tests/RunCMake/FPHSA/exact_1.2.cmake b/Tests/RunCMake/FPHSA/exact_1.2.cmake
new file mode 100644
index 0000000..080d961
--- /dev/null
+++ b/Tests/RunCMake/FPHSA/exact_1.2.cmake
@@ -0,0 +1 @@
+find_package(Pseudo 1.2 EXACT REQUIRED)
diff --git a/Tests/RunCMake/FPHSA/exact_1.3-result.txt b/Tests/RunCMake/FPHSA/exact_1.3-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/FPHSA/exact_1.3-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/FPHSA/exact_1.3.cmake b/Tests/RunCMake/FPHSA/exact_1.3.cmake
new file mode 100644
index 0000000..e36b0c5
--- /dev/null
+++ b/Tests/RunCMake/FPHSA/exact_1.3.cmake
@@ -0,0 +1 @@
+find_package(Pseudo 1.3 EXACT REQUIRED)
diff --git a/Tests/RunCMake/FPHSA/exact_1.cmake b/Tests/RunCMake/FPHSA/exact_1.cmake
new file mode 100644
index 0000000..adadbc4
--- /dev/null
+++ b/Tests/RunCMake/FPHSA/exact_1.cmake
@@ -0,0 +1 @@
+find_package(Pseudo 1 EXACT REQUIRED)
diff --git a/Tests/RunCMake/FPHSA/exact_2-result.txt b/Tests/RunCMake/FPHSA/exact_2-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/FPHSA/exact_2-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/FPHSA/exact_2.cmake b/Tests/RunCMake/FPHSA/exact_2.cmake
new file mode 100644
index 0000000..55353a8
--- /dev/null
+++ b/Tests/RunCMake/FPHSA/exact_2.cmake
@@ -0,0 +1 @@
+find_package(Pseudo 2 EXACT REQUIRED)
diff --git a/Tests/RunCMake/File_Generate/CMakeLists.txt b/Tests/RunCMake/File_Generate/CMakeLists.txt
index 12cd3c7..bc0cf5d 100644
--- a/Tests/RunCMake/File_Generate/CMakeLists.txt
+++ b/Tests/RunCMake/File_Generate/CMakeLists.txt
@@ -1,3 +1,6 @@
 cmake_minimum_required(VERSION 2.8.4)
 project(${RunCMake_TEST} NONE)
-include(${RunCMake_TEST}.cmake)
+if(NOT TEST_FILE)
+  set(TEST_FILE ${RunCMake_TEST}.cmake)
+endif()
+include(${TEST_FILE})
diff --git a/Tests/RunCMake/File_Generate/EmptyCondition1-stderr.txt b/Tests/RunCMake/File_Generate/EmptyCondition1-stderr.txt
index 9fe39cc..e823b25 100644
--- a/Tests/RunCMake/File_Generate/EmptyCondition1-stderr.txt
+++ b/Tests/RunCMake/File_Generate/EmptyCondition1-stderr.txt
@@ -1,4 +1,4 @@
 CMake Error at EmptyCondition1.cmake:2 \(file\):
   file Incorrect arguments to GENERATE subcommand.
 Call Stack \(most recent call first\):
-  CMakeLists.txt:3 \(include\)
+  CMakeLists.txt:[0-9]+ \(include\)
diff --git a/Tests/RunCMake/File_Generate/EmptyCondition2-stderr.txt b/Tests/RunCMake/File_Generate/EmptyCondition2-stderr.txt
index 73d5f25..b042946 100644
--- a/Tests/RunCMake/File_Generate/EmptyCondition2-stderr.txt
+++ b/Tests/RunCMake/File_Generate/EmptyCondition2-stderr.txt
@@ -1,4 +1,4 @@
 CMake Error at EmptyCondition2.cmake:2 \(file\):
   file CONDITION of sub-command GENERATE must not be empty if specified.
 Call Stack \(most recent call first\):
-  CMakeLists.txt:3 \(include\)
+  CMakeLists.txt:[0-9]+ \(include\)
diff --git a/Tests/RunCMake/File_Generate/RunCMakeTest.cmake b/Tests/RunCMake/File_Generate/RunCMakeTest.cmake
index f23fa19..dee0692 100644
--- a/Tests/RunCMake/File_Generate/RunCMakeTest.cmake
+++ b/Tests/RunCMake/File_Generate/RunCMakeTest.cmake
@@ -1,8 +1,8 @@
 include(RunCMake)
 
 run_cmake(CommandConflict)
-if("${RunCMake_GENERATOR}" MATCHES "Visual Studio" OR "${RunCMake_GENERATOR}" MATCHES "XCode" )
-    run_cmake(OutputConflict)
+if("${RunCMake_GENERATOR}" MATCHES "Visual Studio|Xcode" AND NOT XCODE_BELOW_2)
+  run_cmake(OutputConflict)
 endif()
 run_cmake(EmptyCondition1)
 run_cmake(EmptyCondition2)
@@ -12,10 +12,10 @@
 set(timeformat "%Y%j%H%M%S")
 
 file(REMOVE "${RunCMake_BINARY_DIR}/WriteIfDifferent-build/output_file.txt")
-set(RunCMake_TEST_FILE "WriteIfDifferent")
+set(RunCMake_TEST_OPTIONS "-DTEST_FILE=WriteIfDifferent.cmake")
 set(RunCMake_TEST_BINARY_DIR "${RunCMake_BINARY_DIR}/WriteIfDifferent-build")
 run_cmake(WriteIfDifferent-prepare)
-unset(RunCMake_TEST_FILE)
+unset(RunCMake_TEST_OPTIONS)
 unset(RunCMake_TEST_BINARY_DIR)
 file(TIMESTAMP "${RunCMake_BINARY_DIR}/WriteIfDifferent-build/output_file.txt" timestamp ${timeformat})
 if(NOT timestamp)
diff --git a/Tests/RunCMake/FindPkgConfig/FindPkgConfig_NO_PKGCONFIG_PATH.cmake b/Tests/RunCMake/FindPkgConfig/FindPkgConfig_NO_PKGCONFIG_PATH.cmake
index 924976e..89ce4c6 100644
--- a/Tests/RunCMake/FindPkgConfig/FindPkgConfig_NO_PKGCONFIG_PATH.cmake
+++ b/Tests/RunCMake/FindPkgConfig/FindPkgConfig_NO_PKGCONFIG_PATH.cmake
@@ -26,7 +26,7 @@
 
 pkg_check_modules(FOO "${expected_path}")
 
-if(NOT "FOO_FOUND")
+if(NOT FOO_FOUND)
   message(FATAL_ERROR "Expected PKG_CONFIG_PATH: \"${expected_path}\".")
 endif()
 
@@ -36,6 +36,6 @@
 
 pkg_check_modules(BAR "${expected_path}" NO_CMAKE_PATH NO_CMAKE_ENVIRONMENT_PATH)
 
-if(NOT "BAR_FOUND")
+if(NOT BAR_FOUND)
   message(FATAL_ERROR "Expected PKG_CONFIG_PATH: \"${expected_path}\".")
 endif()
diff --git a/Tests/RunCMake/FindPkgConfig/FindPkgConfig_PKGCONFIG_PATH.cmake b/Tests/RunCMake/FindPkgConfig/FindPkgConfig_PKGCONFIG_PATH.cmake
index 4a66e85..c903279 100644
--- a/Tests/RunCMake/FindPkgConfig/FindPkgConfig_PKGCONFIG_PATH.cmake
+++ b/Tests/RunCMake/FindPkgConfig/FindPkgConfig_PKGCONFIG_PATH.cmake
@@ -46,6 +46,6 @@
 
 pkg_check_modules(FOO "${expected_path}")
 
-if(NOT "FOO_FOUND")
+if(NOT FOO_FOUND)
   message(FATAL_ERROR "Expected PKG_CONFIG_PATH: \"${expected_path}\".")
 endif()
diff --git a/Tests/RunCMake/FindPkgConfig/FindPkgConfig_PKGCONFIG_PATH_NO_CMAKE_ENVIRONMENT_PATH.cmake b/Tests/RunCMake/FindPkgConfig/FindPkgConfig_PKGCONFIG_PATH_NO_CMAKE_ENVIRONMENT_PATH.cmake
index 0b057b8..a52bcbf 100644
--- a/Tests/RunCMake/FindPkgConfig/FindPkgConfig_PKGCONFIG_PATH_NO_CMAKE_ENVIRONMENT_PATH.cmake
+++ b/Tests/RunCMake/FindPkgConfig/FindPkgConfig_PKGCONFIG_PATH_NO_CMAKE_ENVIRONMENT_PATH.cmake
@@ -46,6 +46,6 @@
 
 pkg_check_modules(FOO "${expected_path}" NO_CMAKE_ENVIRONMENT_PATH)
 
-if(NOT "FOO_FOUND")
+if(NOT FOO_FOUND)
   message(FATAL_ERROR "Expected PKG_CONFIG_PATH: \"${expected_path}\".")
 endif()
diff --git a/Tests/RunCMake/FindPkgConfig/FindPkgConfig_PKGCONFIG_PATH_NO_CMAKE_PATH.cmake b/Tests/RunCMake/FindPkgConfig/FindPkgConfig_PKGCONFIG_PATH_NO_CMAKE_PATH.cmake
index a3154f1..2fabe5b 100644
--- a/Tests/RunCMake/FindPkgConfig/FindPkgConfig_PKGCONFIG_PATH_NO_CMAKE_PATH.cmake
+++ b/Tests/RunCMake/FindPkgConfig/FindPkgConfig_PKGCONFIG_PATH_NO_CMAKE_PATH.cmake
@@ -46,6 +46,6 @@
 
 pkg_check_modules(FOO "${expected_path}" NO_CMAKE_PATH)
 
-if(NOT "FOO_FOUND")
+if(NOT FOO_FOUND)
   message(FATAL_ERROR "Expected PKG_CONFIG_PATH: \"${expected_path}\".")
 endif()
diff --git a/Tests/RunCMake/GeneratorExpression/NonValidCompiler-TARGET_PDB_FILE-result.txt b/Tests/RunCMake/GeneratorExpression/NonValidCompiler-TARGET_PDB_FILE-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/NonValidCompiler-TARGET_PDB_FILE-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/GeneratorExpression/NonValidCompiler-TARGET_PDB_FILE-stderr.txt b/Tests/RunCMake/GeneratorExpression/NonValidCompiler-TARGET_PDB_FILE-stderr.txt
new file mode 100644
index 0000000..831edad
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/NonValidCompiler-TARGET_PDB_FILE-stderr.txt
@@ -0,0 +1,8 @@
+CMake Error at NonValidCompiler-TARGET_PDB_FILE.cmake:6 \(file\):
+  Error evaluating generator expression:
+
+    \$<TARGET_PDB_FILE:empty>
+
+  TARGET_PDB_FILE is not supported by the target linker.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/GeneratorExpression/NonValidCompiler-TARGET_PDB_FILE.cmake b/Tests/RunCMake/GeneratorExpression/NonValidCompiler-TARGET_PDB_FILE.cmake
new file mode 100644
index 0000000..84a2b2e
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/NonValidCompiler-TARGET_PDB_FILE.cmake
@@ -0,0 +1,9 @@
+
+enable_language(C)
+
+add_library(empty STATIC empty.c)
+
+file(GENERATE
+  OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/test.txt"
+  CONTENT "[$<TARGET_PDB_FILE:empty>]"
+)
diff --git a/Tests/RunCMake/GeneratorExpression/NonValidTarget-TARGET_PDB_FILE-result.txt b/Tests/RunCMake/GeneratorExpression/NonValidTarget-TARGET_PDB_FILE-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/NonValidTarget-TARGET_PDB_FILE-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/GeneratorExpression/NonValidTarget-TARGET_PDB_FILE-stderr.txt b/Tests/RunCMake/GeneratorExpression/NonValidTarget-TARGET_PDB_FILE-stderr.txt
new file mode 100644
index 0000000..e5f21e2
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/NonValidTarget-TARGET_PDB_FILE-stderr.txt
@@ -0,0 +1,8 @@
+CMake Error at NonValidTarget-TARGET_PDB_FILE.cmake:6 \(file\):
+  Error evaluating generator expression:
+
+    \$<TARGET_PDB_FILE:empty>
+
+  TARGET_PDB_FILE is allowed only for targets with linker created artifacts.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/GeneratorExpression/NonValidTarget-TARGET_PDB_FILE.cmake b/Tests/RunCMake/GeneratorExpression/NonValidTarget-TARGET_PDB_FILE.cmake
new file mode 100644
index 0000000..84a2b2e
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/NonValidTarget-TARGET_PDB_FILE.cmake
@@ -0,0 +1,9 @@
+
+enable_language(C)
+
+add_library(empty STATIC empty.c)
+
+file(GENERATE
+  OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/test.txt"
+  CONTENT "[$<TARGET_PDB_FILE:empty>]"
+)
diff --git a/Tests/RunCMake/GeneratorExpression/RunCMakeTest.cmake b/Tests/RunCMake/GeneratorExpression/RunCMakeTest.cmake
index c8f3fdf..6c32393 100644
--- a/Tests/RunCMake/GeneratorExpression/RunCMakeTest.cmake
+++ b/Tests/RunCMake/GeneratorExpression/RunCMakeTest.cmake
@@ -16,3 +16,10 @@
 run_cmake(NonValidTarget-CXX_COMPILER_VERSION)
 run_cmake(NonValidTarget-TARGET_PROPERTY)
 run_cmake(NonValidTarget-TARGET_POLICY)
+
+if(LINKER_SUPPORTS_PDB)
+  run_cmake(NonValidTarget-TARGET_PDB_FILE)
+  run_cmake(ValidTarget-TARGET_PDB_FILE)
+else()
+  run_cmake(NonValidCompiler-TARGET_PDB_FILE)
+endif()
diff --git a/Tests/RunCMake/GeneratorExpression/ValidTarget-TARGET_PDB_FILE-check.cmake b/Tests/RunCMake/GeneratorExpression/ValidTarget-TARGET_PDB_FILE-check.cmake
new file mode 100644
index 0000000..748d14f
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/ValidTarget-TARGET_PDB_FILE-check.cmake
@@ -0,0 +1,17 @@
+file(STRINGS ${RunCMake_TEST_BINARY_DIR}/test.txt TEST_TXT)
+
+list(GET TEST_TXT 0 PDB_PATH)
+list(GET TEST_TXT 1 PDB_NAME)
+list(GET TEST_TXT 2 PDB_DIR)
+
+if(NOT PDB_PATH MATCHES "empty\\.pdb")
+  message(FATAL_ERROR "unexpected PDB_PATH [${PDB_PATH}]")
+endif()
+
+if(NOT PDB_NAME STREQUAL "empty.pdb")
+  message(FATAL_ERROR "unexpected PDB_NAME [${PDB_NAME}]")
+endif()
+
+if(PDB_DIR MATCHES "empty\\.pdb")
+  message(FATAL_ERROR "unexpected PDB_DIR [${PDB_DIR}]")
+endif()
diff --git a/Tests/RunCMake/GeneratorExpression/ValidTarget-TARGET_PDB_FILE-stderr.txt b/Tests/RunCMake/GeneratorExpression/ValidTarget-TARGET_PDB_FILE-stderr.txt
new file mode 100644
index 0000000..10f3293
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/ValidTarget-TARGET_PDB_FILE-stderr.txt
@@ -0,0 +1 @@
+^$
diff --git a/Tests/RunCMake/GeneratorExpression/ValidTarget-TARGET_PDB_FILE.cmake b/Tests/RunCMake/GeneratorExpression/ValidTarget-TARGET_PDB_FILE.cmake
new file mode 100644
index 0000000..38e47f9
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/ValidTarget-TARGET_PDB_FILE.cmake
@@ -0,0 +1,19 @@
+
+enable_language(C)
+
+add_library(empty SHARED empty.c)
+
+if(CMAKE_CONFIGURATION_TYPES)
+  list(GET CMAKE_CONFIGURATION_TYPES 0 FIRST_CONFIG)
+  set(GENERATE_CONDITION CONDITION $<CONFIG:${FIRST_CONFIG}>)
+endif()
+
+file(GENERATE
+  OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/test.txt"
+  CONTENT
+[[$<TARGET_PDB_FILE:empty>
+$<TARGET_PDB_FILE_NAME:empty>
+$<TARGET_PDB_FILE_DIR:empty>
+]]
+  ${GENERATE_CONDITION}
+)
diff --git a/Tests/RunCMake/GeneratorPlatform/BadPlatform-result.txt b/Tests/RunCMake/GeneratorPlatform/BadPlatform-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/GeneratorPlatform/BadPlatform-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/GeneratorPlatform/BadPlatform-stderr.txt b/Tests/RunCMake/GeneratorPlatform/BadPlatform-stderr.txt
new file mode 100644
index 0000000..e315714
--- /dev/null
+++ b/Tests/RunCMake/GeneratorPlatform/BadPlatform-stderr.txt
@@ -0,0 +1,10 @@
+CMake Error at CMakeLists.txt:[0-9]+ \(project\):
+  Generator
+
+    .*
+
+  does not support platform specification, but platform
+
+    Bad Platform
+
+  was specified.$
diff --git a/Tests/RunCMake/GeneratorPlatform/BadPlatform-toolchain.cmake b/Tests/RunCMake/GeneratorPlatform/BadPlatform-toolchain.cmake
new file mode 100644
index 0000000..1c544b0
--- /dev/null
+++ b/Tests/RunCMake/GeneratorPlatform/BadPlatform-toolchain.cmake
@@ -0,0 +1 @@
+set(CMAKE_GENERATOR_PLATFORM "Bad Platform")
diff --git a/Tests/RunCMake/GeneratorPlatform/BadPlatform.cmake b/Tests/RunCMake/GeneratorPlatform/BadPlatform.cmake
new file mode 100644
index 0000000..2fc38e5
--- /dev/null
+++ b/Tests/RunCMake/GeneratorPlatform/BadPlatform.cmake
@@ -0,0 +1 @@
+message(FATAL_ERROR "This should not be reached!")
diff --git a/Tests/RunCMake/GeneratorPlatform/BadPlatformToolchain-result.txt b/Tests/RunCMake/GeneratorPlatform/BadPlatformToolchain-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/GeneratorPlatform/BadPlatformToolchain-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/GeneratorPlatform/BadPlatformToolchain-stderr.txt b/Tests/RunCMake/GeneratorPlatform/BadPlatformToolchain-stderr.txt
new file mode 100644
index 0000000..e315714
--- /dev/null
+++ b/Tests/RunCMake/GeneratorPlatform/BadPlatformToolchain-stderr.txt
@@ -0,0 +1,10 @@
+CMake Error at CMakeLists.txt:[0-9]+ \(project\):
+  Generator
+
+    .*
+
+  does not support platform specification, but platform
+
+    Bad Platform
+
+  was specified.$
diff --git a/Tests/RunCMake/GeneratorPlatform/BadPlatformToolchain.cmake b/Tests/RunCMake/GeneratorPlatform/BadPlatformToolchain.cmake
new file mode 100644
index 0000000..2fc38e5
--- /dev/null
+++ b/Tests/RunCMake/GeneratorPlatform/BadPlatformToolchain.cmake
@@ -0,0 +1 @@
+message(FATAL_ERROR "This should not be reached!")
diff --git a/Tests/RunCMake/GeneratorPlatform/CMakeLists.txt b/Tests/RunCMake/GeneratorPlatform/CMakeLists.txt
new file mode 100644
index 0000000..12cd3c7
--- /dev/null
+++ b/Tests/RunCMake/GeneratorPlatform/CMakeLists.txt
@@ -0,0 +1,3 @@
+cmake_minimum_required(VERSION 2.8.4)
+project(${RunCMake_TEST} NONE)
+include(${RunCMake_TEST}.cmake)
diff --git a/Tests/RunCMake/GeneratorPlatform/NoPlatform-result.txt b/Tests/RunCMake/GeneratorPlatform/NoPlatform-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/GeneratorPlatform/NoPlatform-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/GeneratorPlatform/NoPlatform-stderr.txt b/Tests/RunCMake/GeneratorPlatform/NoPlatform-stderr.txt
new file mode 100644
index 0000000..e1c0da4
--- /dev/null
+++ b/Tests/RunCMake/GeneratorPlatform/NoPlatform-stderr.txt
@@ -0,0 +1,4 @@
+CMake Error at NoPlatform.cmake:2 \(message\):
+  CMAKE_GENERATOR_PLATFORM is empty as expected.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/GeneratorPlatform/NoPlatform.cmake b/Tests/RunCMake/GeneratorPlatform/NoPlatform.cmake
new file mode 100644
index 0000000..1e0ca6d
--- /dev/null
+++ b/Tests/RunCMake/GeneratorPlatform/NoPlatform.cmake
@@ -0,0 +1,7 @@
+if("x${CMAKE_GENERATOR_PLATFORM}" STREQUAL "x")
+  message(FATAL_ERROR "CMAKE_GENERATOR_PLATFORM is empty as expected.")
+else()
+  message(FATAL_ERROR
+    "CMAKE_GENERATOR_PLATFORM is \"${CMAKE_GENERATOR_PLATFORM}\" "
+    "but should be empty!")
+endif()
diff --git a/Tests/RunCMake/GeneratorPlatform/RunCMakeTest.cmake b/Tests/RunCMake/GeneratorPlatform/RunCMakeTest.cmake
new file mode 100644
index 0000000..4d0a0a1
--- /dev/null
+++ b/Tests/RunCMake/GeneratorPlatform/RunCMakeTest.cmake
@@ -0,0 +1,28 @@
+include(RunCMake)
+
+set(RunCMake_GENERATOR_PLATFORM "")
+run_cmake(NoPlatform)
+
+if("${RunCMake_GENERATOR}" MATCHES "^Visual Studio ([89]|1[0124])( 20[0-9][0-9])?$")
+  set(RunCMake_GENERATOR_PLATFORM "x64")
+  run_cmake(x64Platform)
+else()
+  set(RunCMake_GENERATOR_PLATFORM "Bad Platform")
+  run_cmake(BadPlatform)
+endif()
+
+set(RunCMake_GENERATOR_TOOLSET "")
+
+set(RunCMake_TEST_OPTIONS -A "Extra Platform")
+run_cmake(TwoPlatforms)
+unset(RunCMake_TEST_OPTIONS)
+
+if("${RunCMake_GENERATOR}" MATCHES "^Visual Studio ([89]|1[0124])( 20[0-9][0-9])?$")
+  set(RunCMake_TEST_OPTIONS -DCMAKE_TOOLCHAIN_FILE=${RunCMake_SOURCE_DIR}/TestPlatform-toolchain.cmake)
+  run_cmake(TestPlatformToolchain)
+  unset(RunCMake_TEST_OPTIONS)
+else()
+  set(RunCMake_TEST_OPTIONS -DCMAKE_TOOLCHAIN_FILE=${RunCMake_SOURCE_DIR}/BadPlatform-toolchain.cmake)
+  run_cmake(BadPlatformToolchain)
+  unset(RunCMake_TEST_OPTIONS)
+endif()
diff --git a/Tests/RunCMake/GeneratorPlatform/TestPlatform-toolchain.cmake b/Tests/RunCMake/GeneratorPlatform/TestPlatform-toolchain.cmake
new file mode 100644
index 0000000..763478c
--- /dev/null
+++ b/Tests/RunCMake/GeneratorPlatform/TestPlatform-toolchain.cmake
@@ -0,0 +1 @@
+set(CMAKE_GENERATOR_PLATFORM "Test Platform")
diff --git a/Tests/RunCMake/GeneratorPlatform/TestPlatformToolchain-result.txt b/Tests/RunCMake/GeneratorPlatform/TestPlatformToolchain-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/GeneratorPlatform/TestPlatformToolchain-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/GeneratorPlatform/TestPlatformToolchain-stderr.txt b/Tests/RunCMake/GeneratorPlatform/TestPlatformToolchain-stderr.txt
new file mode 100644
index 0000000..b9bb3b2
--- /dev/null
+++ b/Tests/RunCMake/GeneratorPlatform/TestPlatformToolchain-stderr.txt
@@ -0,0 +1,9 @@
+CMake Error at TestPlatformToolchain.cmake:[0-9]+ \(message\):
+  CMAKE_GENERATOR_PLATFORM is "Test Platform" as expected.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:3 \(include\)
++
+CMake Error at TestPlatformToolchain.cmake:[0-9]+ \(message\):
+  CMAKE_VS_PLATFORM_NAME is "Test Platform" as expected.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/GeneratorPlatform/TestPlatformToolchain.cmake b/Tests/RunCMake/GeneratorPlatform/TestPlatformToolchain.cmake
new file mode 100644
index 0000000..c4430a5
--- /dev/null
+++ b/Tests/RunCMake/GeneratorPlatform/TestPlatformToolchain.cmake
@@ -0,0 +1,16 @@
+if("x${CMAKE_GENERATOR_PLATFORM}" STREQUAL "xTest Platform")
+  message(SEND_ERROR "CMAKE_GENERATOR_PLATFORM is \"Test Platform\" as expected.")
+else()
+  message(FATAL_ERROR
+    "CMAKE_GENERATOR_PLATFORM is \"${CMAKE_GENERATOR_PLATFORM}\" "
+    "but should be \"Test Platform\"!")
+endif()
+if(CMAKE_GENERATOR MATCHES "Visual Studio")
+  if("x${CMAKE_VS_PLATFORM_NAME}" STREQUAL "xTest Platform")
+    message(SEND_ERROR "CMAKE_VS_PLATFORM_NAME is \"Test Platform\" as expected.")
+  else()
+    message(FATAL_ERROR
+      "CMAKE_VS_PLATFORM_NAME is \"${CMAKE_VS_PLATFORM_NAME}\" "
+      "but should be \"Test Platform\"!")
+  endif()
+endif()
diff --git a/Tests/RunCMake/GeneratorPlatform/TwoPlatforms-result.txt b/Tests/RunCMake/GeneratorPlatform/TwoPlatforms-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/GeneratorPlatform/TwoPlatforms-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/GeneratorPlatform/TwoPlatforms-stderr.txt b/Tests/RunCMake/GeneratorPlatform/TwoPlatforms-stderr.txt
new file mode 100644
index 0000000..90e4eca
--- /dev/null
+++ b/Tests/RunCMake/GeneratorPlatform/TwoPlatforms-stderr.txt
@@ -0,0 +1 @@
+CMake Error: Multiple -A options not allowed
diff --git a/Tests/RunCMake/GeneratorPlatform/TwoPlatforms.cmake b/Tests/RunCMake/GeneratorPlatform/TwoPlatforms.cmake
new file mode 100644
index 0000000..2fc38e5
--- /dev/null
+++ b/Tests/RunCMake/GeneratorPlatform/TwoPlatforms.cmake
@@ -0,0 +1 @@
+message(FATAL_ERROR "This should not be reached!")
diff --git a/Tests/RunCMake/GeneratorPlatform/x64Platform-stdout.txt b/Tests/RunCMake/GeneratorPlatform/x64Platform-stdout.txt
new file mode 100644
index 0000000..05a83ff
--- /dev/null
+++ b/Tests/RunCMake/GeneratorPlatform/x64Platform-stdout.txt
@@ -0,0 +1,2 @@
+-- CMAKE_GENERATOR_PLATFORM is 'x64' as expected.
+-- CMAKE_VS_PLATFORM_NAME is 'x64' as expected.
diff --git a/Tests/RunCMake/GeneratorPlatform/x64Platform.cmake b/Tests/RunCMake/GeneratorPlatform/x64Platform.cmake
new file mode 100644
index 0000000..a23bdc7
--- /dev/null
+++ b/Tests/RunCMake/GeneratorPlatform/x64Platform.cmake
@@ -0,0 +1,7 @@
+foreach(v CMAKE_GENERATOR_PLATFORM CMAKE_VS_PLATFORM_NAME)
+  if("x${${v}}" STREQUAL "xx64")
+    message(STATUS "${v} is 'x64' as expected.")
+  else()
+    message(FATAL_ERROR "${v} is '${${v}}' but should be 'x64'!")
+  endif()
+endforeach()
diff --git a/Tests/RunCMake/GeneratorToolset/RunCMakeTest.cmake b/Tests/RunCMake/GeneratorToolset/RunCMakeTest.cmake
index d39f33f..6220657 100644
--- a/Tests/RunCMake/GeneratorToolset/RunCMakeTest.cmake
+++ b/Tests/RunCMake/GeneratorToolset/RunCMakeTest.cmake
@@ -3,7 +3,7 @@
 set(RunCMake_GENERATOR_TOOLSET "")
 run_cmake(NoToolset)
 
-if("${RunCMake_GENERATOR}" MATCHES "Visual Studio 1[012]|Xcode" AND NOT XCODE_BELOW_3)
+if("${RunCMake_GENERATOR}" MATCHES "Visual Studio 1[0124]|Xcode" AND NOT XCODE_BELOW_3)
   set(RunCMake_GENERATOR_TOOLSET "Test Toolset")
   run_cmake(TestToolset)
 else()
@@ -17,7 +17,7 @@
 run_cmake(TwoToolsets)
 unset(RunCMake_TEST_OPTIONS)
 
-if("${RunCMake_GENERATOR}" MATCHES "Visual Studio 1[012]|Xcode" AND NOT XCODE_BELOW_3)
+if("${RunCMake_GENERATOR}" MATCHES "Visual Studio 1[0124]|Xcode" AND NOT XCODE_BELOW_3)
   set(RunCMake_TEST_OPTIONS -DCMAKE_TOOLCHAIN_FILE=${RunCMake_SOURCE_DIR}/TestToolset-toolchain.cmake)
   run_cmake(TestToolsetToolchain)
   unset(RunCMake_TEST_OPTIONS)
diff --git a/Tests/RunCMake/Languages/LINK_LANGUAGE-genex-stderr.txt b/Tests/RunCMake/Languages/LINK_LANGUAGE-genex-stderr.txt
index a5d5d50..3a7f480 100644
--- a/Tests/RunCMake/Languages/LINK_LANGUAGE-genex-stderr.txt
+++ b/Tests/RunCMake/Languages/LINK_LANGUAGE-genex-stderr.txt
@@ -1,7 +1,9 @@
-CMake Error:
+CMake Error at LINK_LANGUAGE-genex.cmake:[0-9]+ \(target_link_libraries\):
   Error evaluating generator expression:
 
     \$<TARGET_PROPERTY:LINKER_LANGUAGE>
 
   LINKER_LANGUAGE target property can not be used while evaluating link
-  libraries
+  libraries for a static library
+Call Stack \(most recent call first\):
+  CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/Languages/link-libraries-TARGET_FILE-genex-stderr.txt b/Tests/RunCMake/Languages/link-libraries-TARGET_FILE-genex-stderr.txt
index 2d7a3c9..d8bc238 100644
--- a/Tests/RunCMake/Languages/link-libraries-TARGET_FILE-genex-stderr.txt
+++ b/Tests/RunCMake/Languages/link-libraries-TARGET_FILE-genex-stderr.txt
@@ -1,7 +1,9 @@
-CMake Error:
+CMake Error at link-libraries-TARGET_FILE-genex.cmake:[0-9]+ \(target_link_libraries\):
   Error evaluating generator expression:
 
     \$<TARGET_FILE:foo>
 
   Expressions which require the linker language may not be used while
   evaluating link libraries
+Call Stack \(most recent call first\):
+  CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/ObjectLibrary/BadObjSource1-stderr.txt b/Tests/RunCMake/ObjectLibrary/BadObjSource1-stderr.txt
index b31225b..a09552b 100644
--- a/Tests/RunCMake/ObjectLibrary/BadObjSource1-stderr.txt
+++ b/Tests/RunCMake/ObjectLibrary/BadObjSource1-stderr.txt
@@ -3,6 +3,7 @@
 
     bad.def
 
-  but may contain only headers and sources that compile.
+  but may contain only sources that compile, header files, and other files
+  that would not affect linking of a normal library.
 Call Stack \(most recent call first\):
   CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/ObjectLibrary/BadObjSource2-stderr.txt b/Tests/RunCMake/ObjectLibrary/BadObjSource2-stderr.txt
index 906cf0b..b91ffd0 100644
--- a/Tests/RunCMake/ObjectLibrary/BadObjSource2-stderr.txt
+++ b/Tests/RunCMake/ObjectLibrary/BadObjSource2-stderr.txt
@@ -3,6 +3,7 @@
 
     bad.obj
 
-  but may contain only headers and sources that compile.
+  but may contain only sources that compile, header files, and other files
+  that would not affect linking of a normal library.
 Call Stack \(most recent call first\):
   CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/RunCMake.cmake b/Tests/RunCMake/RunCMake.cmake
index 4ed2f43..56d69c8 100644
--- a/Tests/RunCMake/RunCMake.cmake
+++ b/Tests/RunCMake/RunCMake.cmake
@@ -38,9 +38,6 @@
   if(NOT DEFINED RunCMake_TEST_OPTIONS)
     set(RunCMake_TEST_OPTIONS "")
   endif()
-  if (NOT RunCMake_TEST_FILE)
-    set(RunCMake_TEST_FILE "${test}")
-  endif()
   if(APPLE)
     list(APPEND RunCMake_TEST_OPTIONS -DCMAKE_POLICY_DEFAULT_CMP0025=NEW)
   endif()
@@ -56,8 +53,9 @@
     execute_process(
       COMMAND ${CMAKE_COMMAND} "${RunCMake_TEST_SOURCE_DIR}"
                 -G "${RunCMake_GENERATOR}"
+                -A "${RunCMake_GENERATOR_PLATFORM}"
                 -T "${RunCMake_GENERATOR_TOOLSET}"
-                -DRunCMake_TEST=${RunCMake_TEST_FILE}
+                -DRunCMake_TEST=${test}
                 --no-warn-unused-cli
                 ${RunCMake_TEST_OPTIONS}
       WORKING_DIRECTORY "${RunCMake_TEST_BINARY_DIR}"
diff --git a/Tests/RunCMake/Syntax/Unquoted1-stderr.txt b/Tests/RunCMake/Syntax/Unquoted1-stderr.txt
index ff8194a..85a7a9d 100644
--- a/Tests/RunCMake/Syntax/Unquoted1-stderr.txt
+++ b/Tests/RunCMake/Syntax/Unquoted1-stderr.txt
@@ -1 +1 @@
-^\[\]\[=\]\[\$\$\(MV\)-DSTR=" \[="\[;\]$
+^\[\]\[=\]\[\$\$\(MV\)-DSTR=" \[="\[;\]\]\[$
diff --git a/Tests/RunCMake/Syntax/Unquoted1.cmake b/Tests/RunCMake/Syntax/Unquoted1.cmake
index 0344fbd..515161f 100644
--- a/Tests/RunCMake/Syntax/Unquoted1.cmake
+++ b/Tests/RunCMake/Syntax/Unquoted1.cmake
@@ -1 +1 @@
-message([] [=] [$ $(MV) -DSTR=" [=" [;])
+message([] [=] [$ $(MV) -DSTR=" [=" [;] ] [)
diff --git a/Tests/RunCMake/TargetObjects/BadContext-stderr.txt b/Tests/RunCMake/TargetObjects/BadContext-stderr.txt
index 92f2c91..b78189e 100644
--- a/Tests/RunCMake/TargetObjects/BadContext-stderr.txt
+++ b/Tests/RunCMake/TargetObjects/BadContext-stderr.txt
@@ -1,4 +1,4 @@
-CMake Error at BadContext.cmake:2 \(file\):
+(CMake Error at BadContext.cmake:4 \(file\):
   Error evaluating generator expression:
 
     \$<TARGET_OBJECTS:NoTarget>
@@ -7,7 +7,17 @@
   for consumption by CMake.  It is not suitable for writing out elsewhere.
 Call Stack \(most recent call first\):
   CMakeLists.txt:3 \(include\)
-+
+*)+
+(CMake Error at BadContext.cmake:5 \(file\):
+  Error evaluating generator expression:
+
+    \$<TARGET_OBJECTS:NoTarget>
+
+  The evaluation of the TARGET_OBJECTS generator expression is only suitable
+  for consumption by CMake.  It is not suitable for writing out elsewhere.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:3 \(include\)
+*)+
 CMake Error:
   Error evaluating generator expression:
 
diff --git a/Tests/RunCMake/TargetObjects/BadContext.cmake b/Tests/RunCMake/TargetObjects/BadContext.cmake
index 67962a4..5d7e33e 100644
--- a/Tests/RunCMake/TargetObjects/BadContext.cmake
+++ b/Tests/RunCMake/TargetObjects/BadContext.cmake
@@ -1,4 +1,7 @@
+add_library(iface INTERFACE)
+target_sources(iface INTERFACE $<TARGET_OBJECTS:NoTarget>)
 
 file(GENERATE OUTPUT test_output CONTENT $<TARGET_OBJECTS:NoTarget>)
+file(GENERATE OUTPUT test_output2 CONTENT $<TARGET_PROPERTY:iface,INTERFACE_SOURCES>)
 
 install(FILES $<TARGET_OBJECTS:NoTarget> DESTINATION objects)
diff --git a/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle1-result.txt b/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle1-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle1-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle1-stderr.txt b/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle1-stderr.txt
new file mode 100644
index 0000000..7e002f5
--- /dev/null
+++ b/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle1-stderr.txt
@@ -0,0 +1,10 @@
+CMake Error at LinkImplementationCycle1.cmake:5 \(target_link_libraries\):
+  Error evaluating generator expression:
+
+    \$<TARGET_PROPERTY:INCLUDE_DIRECTORIES>
+
+  \$<TARGET_PROPERTY:...> expression in link libraries evaluation depends on
+  target property which is transitive over the link libraries, creating a
+  recursion.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:8 \(include\)
diff --git a/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle1.cmake b/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle1.cmake
new file mode 100644
index 0000000..4b60214
--- /dev/null
+++ b/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle1.cmake
@@ -0,0 +1,8 @@
+
+add_library(empty1 empty.cpp)
+add_library(empty2 empty.cpp)
+
+target_link_libraries(empty1
+  LINK_PUBLIC
+    $<$<STREQUAL:$<TARGET_PROPERTY:INCLUDE_DIRECTORIES>,/foo/bar>:empty2>
+)
diff --git a/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle2-result.txt b/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle2-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle2-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle2-stderr.txt b/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle2-stderr.txt
new file mode 100644
index 0000000..2f72de6
--- /dev/null
+++ b/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle2-stderr.txt
@@ -0,0 +1,10 @@
+CMake Error at LinkImplementationCycle2.cmake:5 \(target_link_libraries\):
+  Error evaluating generator expression:
+
+    \$<TARGET_PROPERTY:INTERFACE_INCLUDE_DIRECTORIES>
+
+  \$<TARGET_PROPERTY:...> expression in link libraries evaluation depends on
+  target property which is transitive over the link libraries, creating a
+  recursion.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:8 \(include\)
diff --git a/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle2.cmake b/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle2.cmake
new file mode 100644
index 0000000..557eac1
--- /dev/null
+++ b/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle2.cmake
@@ -0,0 +1,8 @@
+
+add_library(empty1 empty.cpp)
+add_library(empty2 empty.cpp)
+
+target_link_libraries(empty1
+  LINK_PUBLIC
+    $<$<STREQUAL:$<TARGET_PROPERTY:INTERFACE_INCLUDE_DIRECTORIES>,/foo/bar>:empty2>
+)
diff --git a/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle3-result.txt b/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle3-result.txt
new file mode 100644
index 0000000..573541a
--- /dev/null
+++ b/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle3-result.txt
@@ -0,0 +1 @@
+0
diff --git a/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle3-stderr.txt b/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle3-stderr.txt
new file mode 100644
index 0000000..10f3293
--- /dev/null
+++ b/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle3-stderr.txt
@@ -0,0 +1 @@
+^$
diff --git a/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle3.cmake b/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle3.cmake
new file mode 100644
index 0000000..0f921d4
--- /dev/null
+++ b/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle3.cmake
@@ -0,0 +1,10 @@
+
+add_library(empty1 empty.cpp)
+add_library(empty2 empty.cpp)
+
+# This is OK, because evaluating the INCLUDE_DIRECTORIES is not affected by
+# the content of the INTERFACE_LINK_LIBRARIES.
+target_link_libraries(empty1
+  INTERFACE
+    $<$<STREQUAL:$<TARGET_PROPERTY:INCLUDE_DIRECTORIES>,/foo/bar>:empty2>
+)
diff --git a/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle4-result.txt b/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle4-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle4-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle4-stderr.txt b/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle4-stderr.txt
new file mode 100644
index 0000000..5cfeb0a
--- /dev/null
+++ b/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle4-stderr.txt
@@ -0,0 +1,8 @@
+CMake Error:
+  Error evaluating generator expression:
+
+    \$<TARGET_PROPERTY:INTERFACE_INCLUDE_DIRECTORIES>
+
+  \$<TARGET_PROPERTY:...> expression in link libraries evaluation depends on
+  target property which is transitive over the link libraries, creating a
+  recursion.
diff --git a/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle4.cmake b/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle4.cmake
new file mode 100644
index 0000000..ab6d0b2
--- /dev/null
+++ b/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle4.cmake
@@ -0,0 +1,14 @@
+
+add_library(empty1 empty.cpp)
+add_library(empty2 empty.cpp)
+
+# The INTERFACE_INCLUDE_DIRECTORIES do not depend on the link interface.
+# On its own, this is fine. It is only when used by empty3 that an error
+# is appropriately issued.
+target_link_libraries(empty1
+  INTERFACE
+    $<$<STREQUAL:$<TARGET_PROPERTY:INTERFACE_INCLUDE_DIRECTORIES>,/foo/bar>:empty2>
+)
+
+add_library(empty3 empty.cpp)
+target_link_libraries(empty3 empty1)
diff --git a/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle5-result.txt b/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle5-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle5-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle5-stderr.txt b/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle5-stderr.txt
new file mode 100644
index 0000000..5cfeb0a
--- /dev/null
+++ b/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle5-stderr.txt
@@ -0,0 +1,8 @@
+CMake Error:
+  Error evaluating generator expression:
+
+    \$<TARGET_PROPERTY:INTERFACE_INCLUDE_DIRECTORIES>
+
+  \$<TARGET_PROPERTY:...> expression in link libraries evaluation depends on
+  target property which is transitive over the link libraries, creating a
+  recursion.
diff --git a/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle5.cmake b/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle5.cmake
new file mode 100644
index 0000000..dc180e3
--- /dev/null
+++ b/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle5.cmake
@@ -0,0 +1,10 @@
+
+add_library(empty1 INTERFACE IMPORTED)
+add_library(empty2 INTERFACE IMPORTED)
+
+set_property(TARGET empty1 PROPERTY INTERFACE_LINK_LIBRARIES
+  $<$<STREQUAL:$<TARGET_PROPERTY:INTERFACE_INCLUDE_DIRECTORIES>,/foo/bar>:empty2>
+)
+
+add_library(empty3 empty.cpp)
+target_link_libraries(empty3 empty1)
diff --git a/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle6-result.txt b/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle6-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle6-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle6-stderr.txt b/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle6-stderr.txt
new file mode 100644
index 0000000..5cfeb0a
--- /dev/null
+++ b/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle6-stderr.txt
@@ -0,0 +1,8 @@
+CMake Error:
+  Error evaluating generator expression:
+
+    \$<TARGET_PROPERTY:INTERFACE_INCLUDE_DIRECTORIES>
+
+  \$<TARGET_PROPERTY:...> expression in link libraries evaluation depends on
+  target property which is transitive over the link libraries, creating a
+  recursion.
diff --git a/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle6.cmake b/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle6.cmake
new file mode 100644
index 0000000..91252d0
--- /dev/null
+++ b/Tests/RunCMake/TargetPropertyGeneratorExpressions/LinkImplementationCycle6.cmake
@@ -0,0 +1,14 @@
+
+add_library(empty1 SHARED empty.cpp)
+add_library(empty2 SHARED empty.cpp)
+
+# The INTERFACE_INCLUDE_DIRECTORIES do not depend on the link interface.
+# On its own, this is fine. It is only when used by empty3 that an error
+# is appropriately issued.
+target_link_libraries(empty1
+  INTERFACE
+    $<$<STREQUAL:$<TARGET_PROPERTY:INTERFACE_INCLUDE_DIRECTORIES>,/foo/bar>:empty2>
+)
+
+add_library(empty3 SHARED empty.cpp)
+target_link_libraries(empty3 empty1)
diff --git a/Tests/RunCMake/TargetPropertyGeneratorExpressions/RunCMakeTest.cmake b/Tests/RunCMake/TargetPropertyGeneratorExpressions/RunCMakeTest.cmake
index 0ee3238..645a57d 100644
--- a/Tests/RunCMake/TargetPropertyGeneratorExpressions/RunCMakeTest.cmake
+++ b/Tests/RunCMake/TargetPropertyGeneratorExpressions/RunCMakeTest.cmake
@@ -15,3 +15,9 @@
 run_cmake(BadInvalidName6)
 run_cmake(BadInvalidName7)
 run_cmake(BadInvalidName8)
+run_cmake(LinkImplementationCycle1)
+run_cmake(LinkImplementationCycle2)
+run_cmake(LinkImplementationCycle3)
+run_cmake(LinkImplementationCycle4)
+run_cmake(LinkImplementationCycle5)
+run_cmake(LinkImplementationCycle6)
diff --git a/Tests/RunCMake/TargetPropertyGeneratorExpressions/empty.cpp b/Tests/RunCMake/TargetPropertyGeneratorExpressions/empty.cpp
new file mode 100644
index 0000000..bfbbdde
--- /dev/null
+++ b/Tests/RunCMake/TargetPropertyGeneratorExpressions/empty.cpp
@@ -0,0 +1,7 @@
+#ifdef _WIN32
+__declspec(dllexport)
+#endif
+int empty()
+{
+  return 0;
+}
diff --git a/Tests/RunCMake/WriteCompilerDetectionHeader/EmptyPrefix-result.txt b/Tests/RunCMake/WriteCompilerDetectionHeader/EmptyPrefix-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/WriteCompilerDetectionHeader/EmptyPrefix-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/WriteCompilerDetectionHeader/EmptyPrefix-stderr.txt b/Tests/RunCMake/WriteCompilerDetectionHeader/EmptyPrefix-stderr.txt
new file mode 100644
index 0000000..cf8578e
--- /dev/null
+++ b/Tests/RunCMake/WriteCompilerDetectionHeader/EmptyPrefix-stderr.txt
@@ -0,0 +1,5 @@
+CMake Error at .*/Modules/WriteCompilerDetectionHeader.cmake:[0-9]+ \(message\):
+  A prefix must be specified
+Call Stack \(most recent call first\):
+  EmptyPrefix.cmake:[0-9]+ \(write_compiler_detection_header\)
+  CMakeLists.txt:[0-9]+ \(include\)
diff --git a/Tests/RunCMake/WriteCompilerDetectionHeader/EmptyPrefix.cmake b/Tests/RunCMake/WriteCompilerDetectionHeader/EmptyPrefix.cmake
new file mode 100644
index 0000000..eda6b18
--- /dev/null
+++ b/Tests/RunCMake/WriteCompilerDetectionHeader/EmptyPrefix.cmake
@@ -0,0 +1,10 @@
+
+include(WriteCompilerDetectionHeader)
+
+write_compiler_detection_header(
+  FILE "${CMAKE_CURRENT_BINARY_DIR}/somefile"
+  PREFIX ""
+  VERSION 3.1
+  COMPILERS GNU
+  FEATURES cxx_final
+)
diff --git a/Tests/RunCMake/WriteCompilerDetectionHeader/InvalidPrefix-result.txt b/Tests/RunCMake/WriteCompilerDetectionHeader/InvalidPrefix-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/WriteCompilerDetectionHeader/InvalidPrefix-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/WriteCompilerDetectionHeader/InvalidPrefix-stderr.txt b/Tests/RunCMake/WriteCompilerDetectionHeader/InvalidPrefix-stderr.txt
new file mode 100644
index 0000000..ea1bf67
--- /dev/null
+++ b/Tests/RunCMake/WriteCompilerDetectionHeader/InvalidPrefix-stderr.txt
@@ -0,0 +1,5 @@
+CMake Error at .*/Modules/WriteCompilerDetectionHeader.cmake:[0-9]+ \(message\):
+  The prefix must be a valid C identifier.
+Call Stack \(most recent call first\):
+  InvalidPrefix.cmake:[0-9]+ \(write_compiler_detection_header\)
+  CMakeLists.txt:[0-9]+ \(include\)
diff --git a/Tests/RunCMake/WriteCompilerDetectionHeader/InvalidPrefix.cmake b/Tests/RunCMake/WriteCompilerDetectionHeader/InvalidPrefix.cmake
new file mode 100644
index 0000000..6599f35
--- /dev/null
+++ b/Tests/RunCMake/WriteCompilerDetectionHeader/InvalidPrefix.cmake
@@ -0,0 +1,10 @@
+
+include(WriteCompilerDetectionHeader)
+
+write_compiler_detection_header(
+  FILE "${CMAKE_CURRENT_BINARY_DIR}/somefile"
+  PREFIX "0compile"
+  VERSION 3.1
+  COMPILERS GNU
+  FEATURES cxx_final
+)
diff --git a/Tests/RunCMake/WriteCompilerDetectionHeader/OldVersion-stderr.txt b/Tests/RunCMake/WriteCompilerDetectionHeader/OldVersion-stderr.txt
index 842eb3f..8d4db34 100644
--- a/Tests/RunCMake/WriteCompilerDetectionHeader/OldVersion-stderr.txt
+++ b/Tests/RunCMake/WriteCompilerDetectionHeader/OldVersion-stderr.txt
@@ -1,5 +1,9 @@
 CMake Error at .*Modules/WriteCompilerDetectionHeader.cmake:[0-9]+ \(message\):
-  VERSION parameter too low.
+  VERSION compatibility for write_compiler_detection_header is set to 3.0,
+  which is too low.  It must be set to at least 3.1.0.  Either set the
+  VERSION parameter to the write_compiler_detection_header function, or
+  update your minimum required CMake version with the cmake_minimum_required
+  command.
 Call Stack \(most recent call first\):
   OldVersion.cmake:4 \(write_compiler_detection_header\)
   CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/WriteCompilerDetectionHeader/RunCMakeTest.cmake b/Tests/RunCMake/WriteCompilerDetectionHeader/RunCMakeTest.cmake
index be79d41..6dded44 100644
--- a/Tests/RunCMake/WriteCompilerDetectionHeader/RunCMakeTest.cmake
+++ b/Tests/RunCMake/WriteCompilerDetectionHeader/RunCMakeTest.cmake
@@ -10,3 +10,5 @@
 run_cmake(InvalidCompiler)
 run_cmake(InvalidFeature)
 run_cmake(InvalidCXXFeature)
+run_cmake(EmptyPrefix)
+run_cmake(InvalidPrefix)
diff --git a/Tests/RunCMake/file/INSTALL-DIRECTORY-stdout.txt b/Tests/RunCMake/file/INSTALL-DIRECTORY-stdout.txt
new file mode 100644
index 0000000..561a6b1
--- /dev/null
+++ b/Tests/RunCMake/file/INSTALL-DIRECTORY-stdout.txt
@@ -0,0 +1,8 @@
+-- Before Installing
+-- Installing: .*/Tests/RunCMake/file/INSTALL-DIRECTORY-build/dir
+-- Installing: .*/Tests/RunCMake/file/INSTALL-DIRECTORY-build/dir/empty.txt
+-- Up-to-date: .*/Tests/RunCMake/file/INSTALL-DIRECTORY-build/dir
+-- Up-to-date: .*/Tests/RunCMake/file/INSTALL-DIRECTORY-build/dir/empty.txt
+-- Up-to-date: .*/Tests/RunCMake/file/INSTALL-DIRECTORY-build/dir
+-- Up-to-date: .*/Tests/RunCMake/file/INSTALL-DIRECTORY-build/dir/empty.txt
+-- After Installing
diff --git a/Tests/RunCMake/file/INSTALL-DIRECTORY.cmake b/Tests/RunCMake/file/INSTALL-DIRECTORY.cmake
new file mode 100644
index 0000000..0bc1d18
--- /dev/null
+++ b/Tests/RunCMake/file/INSTALL-DIRECTORY.cmake
@@ -0,0 +1,10 @@
+set(src ${CMAKE_CURRENT_SOURCE_DIR}/dir)
+set(dst ${CMAKE_CURRENT_BINARY_DIR}/dir)
+file(REMOVE RECURSE ${dst})
+message(STATUS "Before Installing")
+file(INSTALL FILES ${src}/ DESTINATION ${dst} TYPE DIRECTORY)
+file(INSTALL FILES ${src}/ DESTINATION ${dst} TYPE DIRECTORY)
+file(INSTALL FILES ${src}/ DESTINATION ${dst} TYPE DIRECTORY MESSAGE_NEVER)
+file(INSTALL FILES ${src}/ DESTINATION ${dst} TYPE DIRECTORY MESSAGE_LAZY)
+file(INSTALL FILES ${src}/ DESTINATION ${dst} TYPE DIRECTORY MESSAGE_ALWAYS)
+message(STATUS "After Installing")
diff --git a/Tests/RunCMake/file/INSTALL-MESSAGE-bad-result.txt b/Tests/RunCMake/file/INSTALL-MESSAGE-bad-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/file/INSTALL-MESSAGE-bad-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/file/INSTALL-MESSAGE-bad-stderr.txt b/Tests/RunCMake/file/INSTALL-MESSAGE-bad-stderr.txt
new file mode 100644
index 0000000..557b817
--- /dev/null
+++ b/Tests/RunCMake/file/INSTALL-MESSAGE-bad-stderr.txt
@@ -0,0 +1,32 @@
+CMake Error at INSTALL-MESSAGE-bad.cmake:1 \(file\):
+  file INSTALL options MESSAGE_ALWAYS, MESSAGE_LAZY, and MESSAGE_NEVER are
+  mutually exclusive.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:3 \(include\)
++
+CMake Error at INSTALL-MESSAGE-bad.cmake:2 \(file\):
+  file INSTALL options MESSAGE_ALWAYS, MESSAGE_LAZY, and MESSAGE_NEVER are
+  mutually exclusive.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:3 \(include\)
++
+CMake Error at INSTALL-MESSAGE-bad.cmake:3 \(file\):
+  file INSTALL options MESSAGE_ALWAYS, MESSAGE_LAZY, and MESSAGE_NEVER are
+  mutually exclusive.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:3 \(include\)
++
+CMake Error at INSTALL-MESSAGE-bad.cmake:4 \(file\):
+  file option MESSAGE_ALWAYS may not appear after PATTERN or REGEX.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:3 \(include\)
++
+CMake Error at INSTALL-MESSAGE-bad.cmake:5 \(file\):
+  file option MESSAGE_LAZY may not appear after PATTERN or REGEX.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:3 \(include\)
++
+CMake Error at INSTALL-MESSAGE-bad.cmake:6 \(file\):
+  file option MESSAGE_NEVER may not appear after PATTERN or REGEX.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/file/INSTALL-MESSAGE-bad.cmake b/Tests/RunCMake/file/INSTALL-MESSAGE-bad.cmake
new file mode 100644
index 0000000..f878c69
--- /dev/null
+++ b/Tests/RunCMake/file/INSTALL-MESSAGE-bad.cmake
@@ -0,0 +1,6 @@
+file(INSTALL DESTINATION dir MESSAGE_ALWAYS MESSAGE_LAZY)
+file(INSTALL DESTINATION dir MESSAGE_ALWAYS MESSAGE_NEVER)
+file(INSTALL DESTINATION dir MESSAGE_LAZY MESSAGE_NEVER)
+file(INSTALL DESTINATION dir PATTERN *.txt MESSAGE_ALWAYS)
+file(INSTALL DESTINATION dir PATTERN *.txt MESSAGE_LAZY)
+file(INSTALL DESTINATION dir PATTERN *.txt MESSAGE_NEVER)
diff --git a/Tests/RunCMake/file/RunCMakeTest.cmake b/Tests/RunCMake/file/RunCMakeTest.cmake
index 7b05229..bf14263 100644
--- a/Tests/RunCMake/file/RunCMakeTest.cmake
+++ b/Tests/RunCMake/file/RunCMakeTest.cmake
@@ -1,3 +1,5 @@
 include(RunCMake)
 
+run_cmake(INSTALL-DIRECTORY)
+run_cmake(INSTALL-MESSAGE-bad)
 run_cmake(FileOpenFailRead)
diff --git a/Tests/RunCMake/file/dir/empty.txt b/Tests/RunCMake/file/dir/empty.txt
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/Tests/RunCMake/file/dir/empty.txt
diff --git a/Tests/RunCMake/include_directories/BinaryDirectoryInInterface.cmake b/Tests/RunCMake/include_directories/BinaryDirectoryInInterface.cmake
index 8754540..67ee7de 100644
--- a/Tests/RunCMake/include_directories/BinaryDirectoryInInterface.cmake
+++ b/Tests/RunCMake/include_directories/BinaryDirectoryInInterface.cmake
@@ -1,5 +1,5 @@
 
-project(BinaryDirectoryInInterface)
+enable_language(CXX)
 
 add_library(testTarget "${CMAKE_CURRENT_SOURCE_DIR}/empty.cpp")
 target_include_directories(testTarget INTERFACE "${CMAKE_CURRENT_BINARY_DIR}/foo")
diff --git a/Tests/RunCMake/include_directories/CMakeLists.txt b/Tests/RunCMake/include_directories/CMakeLists.txt
index 3482e6b..5cd4825 100644
--- a/Tests/RunCMake/include_directories/CMakeLists.txt
+++ b/Tests/RunCMake/include_directories/CMakeLists.txt
@@ -1,3 +1,6 @@
 cmake_minimum_required(VERSION 3.0)
-project(${RunCMake_TEST} CXX)
-include(${RunCMake_TEST}.cmake)
+project(${RunCMake_TEST} NONE)
+if(NOT TEST_FILE)
+  set(TEST_FILE ${RunCMake_TEST}.cmake)
+endif()
+include(${TEST_FILE})
diff --git a/Tests/RunCMake/include_directories/DebugIncludes-stderr.txt b/Tests/RunCMake/include_directories/DebugIncludes-stderr.txt
index 71e6456..8dff90f 100644
--- a/Tests/RunCMake/include_directories/DebugIncludes-stderr.txt
+++ b/Tests/RunCMake/include_directories/DebugIncludes-stderr.txt
@@ -5,7 +5,7 @@
    \* .*/Tests/RunCMake/include_directories/two
 
 Call Stack \(most recent call first\):
-  CMakeLists.txt:3 \(include\)
+  CMakeLists.txt:[0-9]+ \(include\)
 +
 CMake Debug Log at DebugIncludes.cmake:13 \(set_property\):
   Used includes for target lll:
@@ -13,7 +13,7 @@
    \* .*/Tests/RunCMake/include_directories/three
 
 Call Stack \(most recent call first\):
-  CMakeLists.txt:3 \(include\)
+  CMakeLists.txt:[0-9]+ \(include\)
 +
 CMake Debug Log at DebugIncludes.cmake:18 \(include_directories\):
   Used includes for target lll:
@@ -21,7 +21,7 @@
    \* .*/Tests/RunCMake/include_directories/four
 
 Call Stack \(most recent call first\):
-  CMakeLists.txt:3 \(include\)
+  CMakeLists.txt:[0-9]+ \(include\)
 +
 CMake Debug Log at DebugIncludes.cmake:33 \(set_property\):
   Used includes for target lll:
@@ -33,7 +33,7 @@
 Call Stack \(most recent call first\):
   DebugIncludes.cmake:44 \(some_macro\)
   DebugIncludes.cmake:47 \(some_function\)
-  CMakeLists.txt:3 \(include\)
+  CMakeLists.txt:[0-9]+ \(include\)
 +
 CMake Debug Log at DebugIncludes.cmake:30 \(target_link_libraries\):
   Used includes for target lll:
@@ -41,7 +41,7 @@
    \* .*/Tests/RunCMake/include_directories/eight
 
 Call Stack \(most recent call first\):
-  CMakeLists.txt:3 \(include\)
+  CMakeLists.txt:[0-9]+ \(include\)
 +
 CMake Debug Log at DebugIncludes.cmake:55 \(set_property\):
   Used includes for target lll:
@@ -50,4 +50,4 @@
    \* .*/Tests/RunCMake/include_directories/ten
 
 Call Stack \(most recent call first\):
-  CMakeLists.txt:3 \(include\)
+  CMakeLists.txt:[0-9]+ \(include\)
diff --git a/Tests/RunCMake/include_directories/DebugIncludes.cmake b/Tests/RunCMake/include_directories/DebugIncludes.cmake
index bbc9e46..10a4c50 100644
--- a/Tests/RunCMake/include_directories/DebugIncludes.cmake
+++ b/Tests/RunCMake/include_directories/DebugIncludes.cmake
@@ -1,5 +1,5 @@
 
-project(DebugIncludes)
+enable_language(CXX)
 
 set(CMAKE_DEBUG_TARGET_PROPERTIES INCLUDE_DIRECTORIES)
 
diff --git a/Tests/RunCMake/include_directories/DirInInstallPrefix.cmake b/Tests/RunCMake/include_directories/DirInInstallPrefix.cmake
index d6f08bd..fab7717 100644
--- a/Tests/RunCMake/include_directories/DirInInstallPrefix.cmake
+++ b/Tests/RunCMake/include_directories/DirInInstallPrefix.cmake
@@ -1,4 +1,4 @@
-
+enable_language(CXX)
 add_library(testTarget empty.cpp)
 target_include_directories(testTarget INTERFACE "${CMAKE_INSTALL_PREFIX}/dir")
 
diff --git a/Tests/RunCMake/include_directories/ImportedTarget.cmake b/Tests/RunCMake/include_directories/ImportedTarget.cmake
index e1a20b1..f752f98 100644
--- a/Tests/RunCMake/include_directories/ImportedTarget.cmake
+++ b/Tests/RunCMake/include_directories/ImportedTarget.cmake
@@ -1,5 +1,5 @@
 
-project(ImportedTarget)
+enable_language(CXX)
 
 add_library(testTarget "${CMAKE_CURRENT_SOURCE_DIR}/empty.cpp")
 
diff --git a/Tests/RunCMake/include_directories/InstallPrefixInInterface.cmake b/Tests/RunCMake/include_directories/InstallPrefixInInterface.cmake
index 0f08e58..8d777f5 100644
--- a/Tests/RunCMake/include_directories/InstallPrefixInInterface.cmake
+++ b/Tests/RunCMake/include_directories/InstallPrefixInInterface.cmake
@@ -1,5 +1,5 @@
 
-project(InstallPrefixInInterface)
+enable_language(CXX)
 
 add_library(testTarget "${CMAKE_CURRENT_SOURCE_DIR}/empty.cpp")
 target_include_directories(testTarget INTERFACE "${CMAKE_INSTALL_PREFIX}/foo")
diff --git a/Tests/RunCMake/include_directories/RelativePathInGenex.cmake b/Tests/RunCMake/include_directories/RelativePathInGenex.cmake
index f72cf3a..070a381 100644
--- a/Tests/RunCMake/include_directories/RelativePathInGenex.cmake
+++ b/Tests/RunCMake/include_directories/RelativePathInGenex.cmake
@@ -1,5 +1,5 @@
 
-project(RelativePathInInterface)
+enable_language(CXX)
 
 add_library(testTarget "${CMAKE_CURRENT_SOURCE_DIR}/empty.cpp")
 set_property(TARGET testTarget PROPERTY INTERFACE_INCLUDE_DIRECTORIES "$<1:foo>")
diff --git a/Tests/RunCMake/include_directories/RelativePathInInterface.cmake b/Tests/RunCMake/include_directories/RelativePathInInterface.cmake
index f2ce54a..4c4727d 100644
--- a/Tests/RunCMake/include_directories/RelativePathInInterface.cmake
+++ b/Tests/RunCMake/include_directories/RelativePathInInterface.cmake
@@ -1,5 +1,5 @@
 
-project(RelativePathInInterface)
+enable_language(CXX)
 
 add_library(testTarget "${CMAKE_CURRENT_SOURCE_DIR}/empty.cpp")
 set_property(TARGET testTarget PROPERTY INTERFACE_INCLUDE_DIRECTORIES "foo")
diff --git a/Tests/RunCMake/include_directories/RunCMakeTest.cmake b/Tests/RunCMake/include_directories/RunCMakeTest.cmake
index c5b29d0..fa76f24 100644
--- a/Tests/RunCMake/include_directories/RunCMakeTest.cmake
+++ b/Tests/RunCMake/include_directories/RunCMakeTest.cmake
@@ -31,19 +31,22 @@
   "${RunCMake_BINARY_DIR}/copy/SourceDirectoryInInterface.cmake"
   COPYONLY
 )
-set(RunCMake_TEST_OPTIONS "-DCMAKE_INSTALL_PREFIX=${RunCMake_BINARY_DIR}/copy/SourceDirectoryInInterface/prefix")
-set(RunCMake_TEST_FILE "${RunCMake_BINARY_DIR}/copy/SourceDirectoryInInterface")
+set(RunCMake_TEST_OPTIONS
+  "-DCMAKE_INSTALL_PREFIX=${RunCMake_BINARY_DIR}/copy/SourceDirectoryInInterface/prefix"
+  "-DTEST_FILE=${RunCMake_BINARY_DIR}/copy/SourceDirectoryInInterface.cmake"
+  )
 set(RunCMake_TEST_SOURCE_DIR "${RunCMake_BINARY_DIR}/copy")
 run_cmake(InstallInSrcDir)
 unset(RunCMake_TEST_SOURCE_DIR)
-unset(RunCMake_TEST_FILE)
 
 set(RunCMake_TEST_OPTIONS "-DCMAKE_INSTALL_PREFIX=${RunCMake_BINARY_DIR}/InstallInBinDir-build/prefix")
+set(RunCMake_TEST_OPTIONS
+  "-DCMAKE_INSTALL_PREFIX=${RunCMake_BINARY_DIR}/InstallInBinDir-build/prefix"
+  "-DTEST_FILE=${RunCMake_SOURCE_DIR}/BinaryDirectoryInInterface.cmake"
+  )
 set(RunCMake_TEST_BINARY_DIR "${RunCMake_BINARY_DIR}/InstallInBinDir-build")
-set(RunCMake_TEST_FILE "${RunCMake_SOURCE_DIR}/BinaryDirectoryInInterface")
 run_cmake(InstallInBinDir)
 unset(RunCMake_TEST_BINARY_DIR)
-unset(RunCMake_TEST_FILE)
 
 configure_file(
   "${RunCMake_SOURCE_DIR}/CMakeLists.txt"
@@ -68,22 +71,25 @@
     unset(policyOption)
     set(policyStatus WARN)
   endif()
-  set(RunCMake_TEST_OPTIONS "-DCMAKE_INSTALL_PREFIX=${RunCMake_BINARY_DIR}/prefix" ${policyOption})
+  set(RunCMake_TEST_OPTIONS
+    "-DCMAKE_INSTALL_PREFIX=${RunCMake_BINARY_DIR}/prefix" ${policyOption}
+    "-DTEST_FILE=${RunCMake_SOURCE_DIR}/BinaryDirectoryInInterface.cmake"
+    )
   # Set the RunCMake_TEST_SOURCE_DIR here to the copy too. This is needed to run
   # the test suite in-source properly.  Otherwise the install directory would be
   # a subdirectory or the source directory, which is allowed and tested separately
   # below.
   set(RunCMake_TEST_SOURCE_DIR "${RunCMake_BINARY_DIR}/prefix/src")
   set(RunCMake_TEST_BINARY_DIR "${RunCMake_BINARY_DIR}/prefix/BinInInstallPrefix-CMP0052-${policyStatus}-build")
-  set(RunCMake_TEST_FILE "${RunCMake_SOURCE_DIR}/BinaryDirectoryInInterface")
   run_cmake(BinInInstallPrefix-CMP0052-${policyStatus})
   unset(RunCMake_TEST_BINARY_DIR)
-  unset(RunCMake_TEST_FILE)
 
-  set(RunCMake_TEST_FILE "${RunCMake_BINARY_DIR}/prefix/src/SourceDirectoryInInterface")
+  set(RunCMake_TEST_OPTIONS
+    "-DCMAKE_INSTALL_PREFIX=${RunCMake_BINARY_DIR}/prefix" ${policyOption}
+    "-DTEST_FILE=${RunCMake_BINARY_DIR}/prefix/src/SourceDirectoryInInterface.cmake"
+    )
   run_cmake(SrcInInstallPrefix-CMP0052-${policyStatus})
   unset(RunCMake_TEST_SOURCE_DIR)
-  unset(RunCMake_TEST_FILE)
 endforeach()
 
 set(RunCMake_TEST_OPTIONS "-DCMAKE_INSTALL_PREFIX=${RunCMake_BINARY_DIR}/InstallPrefixInInterface-build/prefix")
@@ -104,12 +110,13 @@
   "${RunCMake_BINARY_DIR}/installToSrc/InstallPrefixInInterface.cmake"
   COPYONLY
 )
-set(RunCMake_TEST_OPTIONS "-DCMAKE_INSTALL_PREFIX=${RunCMake_BINARY_DIR}/installToSrc/InstallPrefixInInterface/prefix")
-set(RunCMake_TEST_FILE "${RunCMake_BINARY_DIR}/installToSrc/InstallPrefixInInterface")
+set(RunCMake_TEST_OPTIONS
+  "-DCMAKE_INSTALL_PREFIX=${RunCMake_BINARY_DIR}/installToSrc/InstallPrefixInInterface/prefix"
+  "-DTEST_FILE=${RunCMake_BINARY_DIR}/installToSrc/InstallPrefixInInterface.cmake"
+  )
 set(RunCMake_TEST_SOURCE_DIR "${RunCMake_BINARY_DIR}/installToSrc")
 run_cmake(InstallToPrefixInSrcDirOutOfSource)
 unset(RunCMake_TEST_SOURCE_DIR)
-unset(RunCMake_TEST_FILE)
 
 
 file(REMOVE_RECURSE "${RunCMake_TEST_BINARY_DIR}/installToSrcInSrc")
@@ -131,12 +138,13 @@
   COPYONLY
 )
 
-set(RunCMake_TEST_OPTIONS "-DCMAKE_INSTALL_PREFIX=${RunCMake_BINARY_DIR}/installToSrcInSrc/InstallPrefixInInterface/prefix")
-set(RunCMake_TEST_FILE "${RunCMake_BINARY_DIR}/installToSrcInSrc/InstallPrefixInInterface")
+set(RunCMake_TEST_OPTIONS
+  "-DCMAKE_INSTALL_PREFIX=${RunCMake_BINARY_DIR}/installToSrcInSrc/InstallPrefixInInterface/prefix"
+  "-DTEST_FILE=${RunCMake_BINARY_DIR}/installToSrcInSrc/InstallPrefixInInterface.cmake"
+  )
 set(RunCMake_TEST_SOURCE_DIR "${RunCMake_BINARY_DIR}/installToSrcInSrc")
 set(RunCMake_TEST_BINARY_DIR "${RunCMake_BINARY_DIR}/installToSrcInSrc")
 run_cmake(InstallToPrefixInSrcDirInSource)
 unset(RunCMake_TEST_SOURCE_DIR)
 unset(RunCMake_TEST_BINARY_DIR)
-unset(RunCMake_TEST_FILE)
 unset(RunCMake_TEST_NO_CLEAN)
diff --git a/Tests/RunCMake/include_directories/SourceDirectoryInInterface.cmake b/Tests/RunCMake/include_directories/SourceDirectoryInInterface.cmake
index c9a9c45..f814a3c 100644
--- a/Tests/RunCMake/include_directories/SourceDirectoryInInterface.cmake
+++ b/Tests/RunCMake/include_directories/SourceDirectoryInInterface.cmake
@@ -1,5 +1,5 @@
 
-project(SourceDirectoryInInterface)
+enable_language(CXX)
 
 add_library(testTarget "${CMAKE_CURRENT_SOURCE_DIR}/empty.cpp")
 target_include_directories(testTarget INTERFACE "${CMAKE_CURRENT_SOURCE_DIR}/foo")
diff --git a/Tests/RunCMake/include_directories/TID-bad-target-stderr.txt b/Tests/RunCMake/include_directories/TID-bad-target-stderr.txt
index 481e358..4e15de1 100644
--- a/Tests/RunCMake/include_directories/TID-bad-target-stderr.txt
+++ b/Tests/RunCMake/include_directories/TID-bad-target-stderr.txt
@@ -1,4 +1,4 @@
 CMake Error at TID-bad-target.cmake:6 \(target_include_directories\):
   target_include_directories called with non-compilable target type
 Call Stack \(most recent call first\):
-  CMakeLists.txt:3 \(include\)
+  CMakeLists.txt:[0-9]+ \(include\)
diff --git a/Tests/RunCMake/include_directories/export-NOWARN.cmake b/Tests/RunCMake/include_directories/export-NOWARN.cmake
index 307ce5a..50720a0 100644
--- a/Tests/RunCMake/include_directories/export-NOWARN.cmake
+++ b/Tests/RunCMake/include_directories/export-NOWARN.cmake
@@ -1,4 +1,4 @@
-
+enable_language(CXX)
 add_library(foo empty.cpp)
 set_property(TARGET foo APPEND PROPERTY INTERFACE_INCLUDE_DIRECTORIES $<0:>/include/subdir)
 set_property(TARGET foo APPEND PROPERTY INTERFACE_INCLUDE_DIRECTORIES $<INSTALL_PREFIX>/include/subdir)
diff --git a/Tests/RunCMake/include_directories/incomplete-genex.cmake b/Tests/RunCMake/include_directories/incomplete-genex.cmake
index b6900a4..976695a 100644
--- a/Tests/RunCMake/include_directories/incomplete-genex.cmake
+++ b/Tests/RunCMake/include_directories/incomplete-genex.cmake
@@ -1,4 +1,4 @@
-project(incomplete-genex)
+enable_language(CXX)
 
 cmake_policy(SET CMP0022 NEW)
 cmake_policy(SET CMP0023 NEW)
diff --git a/Tests/RunCMake/include_external_msproject/check_utils.cmake b/Tests/RunCMake/include_external_msproject/check_utils.cmake
index 7f5ef53..408cadb 100644
--- a/Tests/RunCMake/include_external_msproject/check_utils.cmake
+++ b/Tests/RunCMake/include_external_msproject/check_utils.cmake
@@ -80,7 +80,9 @@
     set(type 8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942)
   endif()
   if(NOT platform)
-    if("${RunCMake_GENERATOR}" MATCHES "Win64")
+    if(RunCMake_GENERATOR_PLATFORM)
+      set(platform "${RunCMake_GENERATOR_PLATFORM}")
+    elseif("${RunCMake_GENERATOR}" MATCHES "Win64")
       set(platform "x64")
     else()
       set(platform "Win32")
diff --git a/Tests/RunCMake/install/DIRECTORY-MESSAGE_NEVER-check.cmake b/Tests/RunCMake/install/DIRECTORY-MESSAGE_NEVER-check.cmake
new file mode 100644
index 0000000..2c716e1
--- /dev/null
+++ b/Tests/RunCMake/install/DIRECTORY-MESSAGE_NEVER-check.cmake
@@ -0,0 +1,13 @@
+file(REMOVE_RECURSE ${RunCMake_TEST_BINARY_DIR}/prefix)
+execute_process(COMMAND ${CMAKE_COMMAND} -P ${RunCMake_TEST_BINARY_DIR}/cmake_install.cmake
+  OUTPUT_VARIABLE out ERROR_VARIABLE err)
+if(out MATCHES "-- Installing: [^\n]*prefix/dir")
+  string(REGEX REPLACE "\n" "\n  " out "  ${out}")
+  set(RunCMake_TEST_FAILED
+    "${RunCMake_TEST_FAILED}Installation output was not quiet:\n${out}")
+endif()
+set(f ${RunCMake_TEST_BINARY_DIR}/prefix/dir/empty.txt)
+if(NOT EXISTS "${f}")
+  set(RunCMake_TEST_FAILED
+    "${RunCMake_TEST_FAILED}File was not installed:\n  ${f}\n")
+endif()
diff --git a/Tests/RunCMake/install/DIRECTORY-MESSAGE_NEVER.cmake b/Tests/RunCMake/install/DIRECTORY-MESSAGE_NEVER.cmake
new file mode 100644
index 0000000..eefb837
--- /dev/null
+++ b/Tests/RunCMake/install/DIRECTORY-MESSAGE_NEVER.cmake
@@ -0,0 +1,3 @@
+set(CMAKE_INSTALL_MESSAGE "ALWAYS")
+set(CMAKE_INSTALL_PREFIX "${CMAKE_BINARY_DIR}/prefix")
+install(DIRECTORY dir/ DESTINATION dir MESSAGE_NEVER)
diff --git a/Tests/RunCMake/install/DIRECTORY-PATTERN-MESSAGE_NEVER-result.txt b/Tests/RunCMake/install/DIRECTORY-PATTERN-MESSAGE_NEVER-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/install/DIRECTORY-PATTERN-MESSAGE_NEVER-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/install/DIRECTORY-PATTERN-MESSAGE_NEVER-stderr.txt b/Tests/RunCMake/install/DIRECTORY-PATTERN-MESSAGE_NEVER-stderr.txt
new file mode 100644
index 0000000..166ba6f
--- /dev/null
+++ b/Tests/RunCMake/install/DIRECTORY-PATTERN-MESSAGE_NEVER-stderr.txt
@@ -0,0 +1,4 @@
+CMake Error at DIRECTORY-PATTERN-MESSAGE_NEVER.cmake:[0-9]+ \(install\):
+  install DIRECTORY does not allow "MESSAGE_NEVER" after PATTERN or REGEX.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/install/DIRECTORY-PATTERN-MESSAGE_NEVER.cmake b/Tests/RunCMake/install/DIRECTORY-PATTERN-MESSAGE_NEVER.cmake
new file mode 100644
index 0000000..de844f7
--- /dev/null
+++ b/Tests/RunCMake/install/DIRECTORY-PATTERN-MESSAGE_NEVER.cmake
@@ -0,0 +1 @@
+install(DIRECTORY src DESTINATION src PATTERN *.txt MESSAGE_NEVER)
diff --git a/Tests/RunCMake/install/DIRECTORY-message-check.cmake b/Tests/RunCMake/install/DIRECTORY-message-check.cmake
new file mode 100644
index 0000000..857681f
--- /dev/null
+++ b/Tests/RunCMake/install/DIRECTORY-message-check.cmake
@@ -0,0 +1,28 @@
+file(REMOVE_RECURSE ${RunCMake_TEST_BINARY_DIR}/prefix)
+execute_process(COMMAND ${CMAKE_COMMAND} -P ${RunCMake_TEST_BINARY_DIR}/cmake_install.cmake
+  OUTPUT_VARIABLE out ERROR_VARIABLE err)
+set(expect "
+-- Installing: [^\n]*/prefix/dir\r?
+-- Installing: [^\n]*/prefix/dir/empty.txt\r?
+")
+if(NOT out MATCHES "${expect}")
+  string(REGEX REPLACE "\n" "\n  " out "  ${out}")
+  set(RunCMake_TEST_FAILED
+    "${RunCMake_TEST_FAILED}First install did not say 'Installing' as expected:\n${out}")
+endif()
+set(f ${RunCMake_TEST_BINARY_DIR}/prefix/dir/empty.txt)
+if(NOT EXISTS "${f}")
+  set(RunCMake_TEST_FAILED
+    "${RunCMake_TEST_FAILED}File was not installed:\n  ${f}\n")
+endif()
+execute_process(COMMAND ${CMAKE_COMMAND} -P ${RunCMake_TEST_BINARY_DIR}/cmake_install.cmake
+  OUTPUT_VARIABLE out ERROR_VARIABLE err)
+set(expect "
+-- Up-to-date: [^\n]*/prefix/dir\r?
+-- Up-to-date: [^\n]*/prefix/dir/empty.txt\r?
+")
+if(NOT out MATCHES "${expect}")
+  string(REGEX REPLACE "\n" "\n  " out "  ${out}")
+  set(RunCMake_TEST_FAILED
+    "${RunCMake_TEST_FAILED}Second install did not say 'Up-to-date' as expected:\n${out}")
+endif()
diff --git a/Tests/RunCMake/install/DIRECTORY-message-lazy-check.cmake b/Tests/RunCMake/install/DIRECTORY-message-lazy-check.cmake
new file mode 100644
index 0000000..c7e6018
--- /dev/null
+++ b/Tests/RunCMake/install/DIRECTORY-message-lazy-check.cmake
@@ -0,0 +1,24 @@
+file(REMOVE_RECURSE ${RunCMake_TEST_BINARY_DIR}/prefix)
+execute_process(COMMAND ${CMAKE_COMMAND} -P ${RunCMake_TEST_BINARY_DIR}/cmake_install.cmake
+  OUTPUT_VARIABLE out ERROR_VARIABLE err)
+set(expect "
+-- Installing: [^\n]*/prefix/dir\r?
+-- Installing: [^\n]*/prefix/dir/empty.txt\r?
+")
+if(NOT out MATCHES "${expect}")
+  string(REGEX REPLACE "\n" "\n  " out "  ${out}")
+  set(RunCMake_TEST_FAILED
+    "${RunCMake_TEST_FAILED}First install did not say 'Installing' as expected:\n${out}")
+endif()
+set(f ${RunCMake_TEST_BINARY_DIR}/prefix/dir/empty.txt)
+if(NOT EXISTS "${f}")
+  set(RunCMake_TEST_FAILED
+    "${RunCMake_TEST_FAILED}File was not installed:\n  ${f}\n")
+endif()
+execute_process(COMMAND ${CMAKE_COMMAND} -P ${RunCMake_TEST_BINARY_DIR}/cmake_install.cmake
+  OUTPUT_VARIABLE out ERROR_VARIABLE err)
+if(out MATCHES "(Installing|Up-to-date)")
+  string(REGEX REPLACE "\n" "\n  " out "  ${out}")
+  set(RunCMake_TEST_FAILED
+    "${RunCMake_TEST_FAILED}Second install was not silent as expected:\n${out}")
+endif()
diff --git a/Tests/RunCMake/install/DIRECTORY-message-lazy.cmake b/Tests/RunCMake/install/DIRECTORY-message-lazy.cmake
new file mode 100644
index 0000000..ed43567
--- /dev/null
+++ b/Tests/RunCMake/install/DIRECTORY-message-lazy.cmake
@@ -0,0 +1,3 @@
+set(CMAKE_INSTALL_MESSAGE "LAZY")
+set(CMAKE_INSTALL_PREFIX "${CMAKE_BINARY_DIR}/prefix")
+install(DIRECTORY dir/ DESTINATION dir)
diff --git a/Tests/RunCMake/install/DIRECTORY-message.cmake b/Tests/RunCMake/install/DIRECTORY-message.cmake
new file mode 100644
index 0000000..913ed15
--- /dev/null
+++ b/Tests/RunCMake/install/DIRECTORY-message.cmake
@@ -0,0 +1,3 @@
+set(CMAKE_INSTALL_MESSAGE "ALWAYS")
+set(CMAKE_INSTALL_PREFIX "${CMAKE_BINARY_DIR}/prefix")
+install(DIRECTORY dir/ DESTINATION dir)
diff --git a/Tests/RunCMake/install/RunCMakeTest.cmake b/Tests/RunCMake/install/RunCMakeTest.cmake
index c8dc379..53b91f3 100644
--- a/Tests/RunCMake/install/RunCMakeTest.cmake
+++ b/Tests/RunCMake/install/RunCMakeTest.cmake
@@ -1,4 +1,8 @@
 include(RunCMake)
+run_cmake(DIRECTORY-MESSAGE_NEVER)
+run_cmake(DIRECTORY-PATTERN-MESSAGE_NEVER)
+run_cmake(DIRECTORY-message)
+run_cmake(DIRECTORY-message-lazy)
 run_cmake(SkipInstallRulesWarning)
 run_cmake(SkipInstallRulesNoWarning1)
 run_cmake(SkipInstallRulesNoWarning2)
diff --git a/Tests/RunCMake/install/dir/empty.txt b/Tests/RunCMake/install/dir/empty.txt
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/Tests/RunCMake/install/dir/empty.txt
diff --git a/Tests/RunCMake/string/RunCMakeTest.cmake b/Tests/RunCMake/string/RunCMakeTest.cmake
index 501acd2..e83db27 100644
--- a/Tests/RunCMake/string/RunCMakeTest.cmake
+++ b/Tests/RunCMake/string/RunCMakeTest.cmake
@@ -2,3 +2,11 @@
 
 run_cmake(Concat)
 run_cmake(ConcatNoArgs)
+
+run_cmake(Uuid)
+run_cmake(UuidMissingNamespace)
+run_cmake(UuidMissingNamespaceValue)
+run_cmake(UuidBadNamespace)
+run_cmake(UuidMissingNameValue)
+run_cmake(UuidMissingTypeValue)
+run_cmake(UuidBadType)
diff --git a/Tests/RunCMake/string/Uuid.cmake b/Tests/RunCMake/string/Uuid.cmake
new file mode 100644
index 0000000..2613d26
--- /dev/null
+++ b/Tests/RunCMake/string/Uuid.cmake
@@ -0,0 +1,17 @@
+set(UUID_DNS_NAMESPACE 6ba7b810-9dad-11d1-80b4-00c04fd430c8)
+
+string(UUID WWW_EXAMPLE_COM_MD5_UUID
+  NAMESPACE ${UUID_DNS_NAMESPACE} NAME www.example.com TYPE MD5)
+
+if(NOT WWW_EXAMPLE_COM_MD5_UUID STREQUAL "5df41881-3aed-3515-88a7-2f4a814cf09e")
+  message(SEND_ERROR
+    "UUID did not create the expected MD5 result: ${WWW_EXAMPLE_COM_MD5_UUID}")
+endif()
+
+string(UUID WWW_EXAMPLE_COM_SHA1_UUID
+  NAMESPACE ${UUID_DNS_NAMESPACE} NAME www.example.com TYPE SHA1 UPPER)
+
+if(NOT WWW_EXAMPLE_COM_SHA1_UUID STREQUAL "2ED6657D-E927-568B-95E1-2665A8AEA6A2")
+  message(SEND_ERROR
+    "UUID did not create the expected SHA1 result: ${WWW_EXAMPLE_COM_SHA1_UUID}")
+endif()
diff --git a/Tests/RunCMake/string/UuidBadNamespace-result.txt b/Tests/RunCMake/string/UuidBadNamespace-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/string/UuidBadNamespace-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/string/UuidBadNamespace-stderr.txt b/Tests/RunCMake/string/UuidBadNamespace-stderr.txt
new file mode 100644
index 0000000..cb12903
--- /dev/null
+++ b/Tests/RunCMake/string/UuidBadNamespace-stderr.txt
@@ -0,0 +1,4 @@
+CMake Error at UuidBadNamespace.cmake:3 \(string\):
+  string UUID sub-command, malformed NAMESPACE UUID.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/string/UuidBadNamespace.cmake b/Tests/RunCMake/string/UuidBadNamespace.cmake
new file mode 100644
index 0000000..f607925
--- /dev/null
+++ b/Tests/RunCMake/string/UuidBadNamespace.cmake
@@ -0,0 +1,4 @@
+set(UUID_DNS_NAMESPACE 6ba7b810-9dad-fooo-80b4-00c04fd430c8)
+
+string(UUID WWW_EXAMPLE_COM_MD5_UUID
+  NAMESPACE ${UUID_DNS_NAMESPACE} NAME www.example.com TYPE MD5)
diff --git a/Tests/RunCMake/string/UuidBadType-result.txt b/Tests/RunCMake/string/UuidBadType-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/string/UuidBadType-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/string/UuidBadType-stderr.txt b/Tests/RunCMake/string/UuidBadType-stderr.txt
new file mode 100644
index 0000000..1993c04
--- /dev/null
+++ b/Tests/RunCMake/string/UuidBadType-stderr.txt
@@ -0,0 +1,4 @@
+CMake Error at UuidBadType.cmake:3 \(string\):
+  string UUID sub-command, unknown TYPE 'FOO'.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/string/UuidBadType.cmake b/Tests/RunCMake/string/UuidBadType.cmake
new file mode 100644
index 0000000..bf4909e
--- /dev/null
+++ b/Tests/RunCMake/string/UuidBadType.cmake
@@ -0,0 +1,4 @@
+set(UUID_DNS_NAMESPACE 6ba7b810-9dad-11d1-80b4-00c04fd430c8)
+
+string(UUID WWW_EXAMPLE_COM_MD5_UUID
+  NAMESPACE ${UUID_DNS_NAMESPACE} NAME www.example.com TYPE FOO)
diff --git a/Tests/RunCMake/string/UuidMissingNameValue-result.txt b/Tests/RunCMake/string/UuidMissingNameValue-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/string/UuidMissingNameValue-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/string/UuidMissingNameValue-stderr.txt b/Tests/RunCMake/string/UuidMissingNameValue-stderr.txt
new file mode 100644
index 0000000..0b7cde4
--- /dev/null
+++ b/Tests/RunCMake/string/UuidMissingNameValue-stderr.txt
@@ -0,0 +1,4 @@
+CMake Error at UuidMissingNameValue.cmake:3 \(string\):
+  string UUID sub-command, NAME requires a value.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/string/UuidMissingNameValue.cmake b/Tests/RunCMake/string/UuidMissingNameValue.cmake
new file mode 100644
index 0000000..407a1d7
--- /dev/null
+++ b/Tests/RunCMake/string/UuidMissingNameValue.cmake
@@ -0,0 +1,4 @@
+set(UUID_DNS_NAMESPACE 6ba7b810-9dad-11d1-80b4-00c04fd430c8)
+
+string(UUID WWW_EXAMPLE_COM_MD5_UUID
+  NAMESPACE ${UUID_DNS_NAMESPACE} TYPE MD5 NAME)
diff --git a/Tests/RunCMake/string/UuidMissingNamespace-result.txt b/Tests/RunCMake/string/UuidMissingNamespace-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/string/UuidMissingNamespace-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/string/UuidMissingNamespace-stderr.txt b/Tests/RunCMake/string/UuidMissingNamespace-stderr.txt
new file mode 100644
index 0000000..dfcfe42
--- /dev/null
+++ b/Tests/RunCMake/string/UuidMissingNamespace-stderr.txt
@@ -0,0 +1,4 @@
+CMake Error at UuidMissingNamespace.cmake:3 \(string\):
+  string UUID sub-command, malformed NAMESPACE UUID.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/string/UuidMissingNamespace.cmake b/Tests/RunCMake/string/UuidMissingNamespace.cmake
new file mode 100644
index 0000000..5a71e4f
--- /dev/null
+++ b/Tests/RunCMake/string/UuidMissingNamespace.cmake
@@ -0,0 +1,4 @@
+set(UUID_DNS_NAMESPACE 6ba7b810-9dad-11d1-80b4-00c04fd430c8)
+
+string(UUID WWW_EXAMPLE_COM_MD5_UUID
+  NAME www.example.com TYPE MD5)
diff --git a/Tests/RunCMake/string/UuidMissingNamespaceValue-result.txt b/Tests/RunCMake/string/UuidMissingNamespaceValue-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/string/UuidMissingNamespaceValue-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/string/UuidMissingNamespaceValue-stderr.txt b/Tests/RunCMake/string/UuidMissingNamespaceValue-stderr.txt
new file mode 100644
index 0000000..86585ad
--- /dev/null
+++ b/Tests/RunCMake/string/UuidMissingNamespaceValue-stderr.txt
@@ -0,0 +1,4 @@
+CMake Error at UuidMissingNamespaceValue.cmake:3 \(string\):
+  string UUID sub-command, NAMESPACE requires a value.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/string/UuidMissingNamespaceValue.cmake b/Tests/RunCMake/string/UuidMissingNamespaceValue.cmake
new file mode 100644
index 0000000..f2219c0
--- /dev/null
+++ b/Tests/RunCMake/string/UuidMissingNamespaceValue.cmake
@@ -0,0 +1,4 @@
+set(UUID_DNS_NAMESPACE 6ba7b810-9dad-11d1-80b4-00c04fd430c8)
+
+string(UUID WWW_EXAMPLE_COM_MD5_UUID
+  NAME www.example.com TYPE MD5 NAMESPACE)
diff --git a/Tests/RunCMake/string/UuidMissingTypeValue-result.txt b/Tests/RunCMake/string/UuidMissingTypeValue-result.txt
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/Tests/RunCMake/string/UuidMissingTypeValue-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/string/UuidMissingTypeValue-stderr.txt b/Tests/RunCMake/string/UuidMissingTypeValue-stderr.txt
new file mode 100644
index 0000000..70252f8
--- /dev/null
+++ b/Tests/RunCMake/string/UuidMissingTypeValue-stderr.txt
@@ -0,0 +1,4 @@
+CMake Error at UuidMissingTypeValue.cmake:3 \(string\):
+  string UUID sub-command, TYPE requires a value.
+Call Stack \(most recent call first\):
+  CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/string/UuidMissingTypeValue.cmake b/Tests/RunCMake/string/UuidMissingTypeValue.cmake
new file mode 100644
index 0000000..6678a46
--- /dev/null
+++ b/Tests/RunCMake/string/UuidMissingTypeValue.cmake
@@ -0,0 +1,4 @@
+set(UUID_DNS_NAMESPACE 6ba7b810-9dad-11d1-80b4-00c04fd430c8)
+
+string(UUID WWW_EXAMPLE_COM_MD5_UUID
+  NAMESPACE ${UUID_DNS_NAMESPACE} NAME www.example.com TYPE)
diff --git a/Tests/StagingPrefix/CMakeLists.txt b/Tests/StagingPrefix/CMakeLists.txt
index 922776d..49ff7fe 100644
--- a/Tests/StagingPrefix/CMakeLists.txt
+++ b/Tests/StagingPrefix/CMakeLists.txt
@@ -38,6 +38,7 @@
     --build-project Producer
     --build-target install
     --build-generator ${CMAKE_GENERATOR}
+    --build-generator-platform "${CMAKE_GENERATOR_PLATFORM}"
     --build-generator-toolset "${CMAKE_GENERATOR_TOOLSET}"
     --build-options
       -DCMAKE_VERBOSE_MAKEFILE=1
@@ -71,6 +72,7 @@
    --build-project Consumer
    --build-target install
    --build-generator ${CMAKE_GENERATOR}
+   --build-generator-platform "${CMAKE_GENERATOR_PLATFORM}"
    --build-generator-toolset "${CMAKE_GENERATOR_TOOLSET}"
    --build-options
       "-DCMAKE_FIND_ROOT_PATH=${CMAKE_BINARY_DIR}/ignored"
diff --git a/Tests/StringFileTest/CMakeLists.txt b/Tests/StringFileTest/CMakeLists.txt
index 4fa5a86..e6c6152 100644
--- a/Tests/StringFileTest/CMakeLists.txt
+++ b/Tests/StringFileTest/CMakeLists.txt
@@ -55,6 +55,16 @@
     "file(STRINGS) incorrectly read from srec file [${infile_strings}]")
 endif()
 
+#this file has utf-8 content
+file(STRINGS test.utf8 infile_strings ENCODING UTF-8)
+list(LENGTH infile_strings content_len)
+if(content_len MATCHES "3")
+  message("file(STRINGS) correctly read from utf8 file [${infile_strings}]")
+else()
+  message(SEND_ERROR
+    "file(STRINGS) incorrectly read from utf8 file [${infile_strings}]")
+endif()
+
 # String test
 string(REGEX MATCH "[cC][mM][aA][kK][eE]" rmvar "CMake is great")
 string(REGEX MATCHALL "[cC][mM][aA][kK][eE]" rmallvar "CMake is better than cmake or CMake")
@@ -113,7 +123,7 @@
 string(STRIP "  ST3" ST3)
 
 foreach(var ST1 ST2 ST3)
-  if("${var}" STREQUAL "${${var}}")
+  if("x${var}" STREQUAL "x${${var}}")
     message("[${var}] == [${${var}}]")
   else()
     message(SEND_ERROR "Problem with the STRIP command for ${var}: [${${var}}]")
diff --git a/Tests/StringFileTest/test.utf8 b/Tests/StringFileTest/test.utf8
new file mode 100644
index 0000000..6c29170
--- /dev/null
+++ b/Tests/StringFileTest/test.utf8
@@ -0,0 +1,3 @@
+The value of π (pi) is 3.141593
+Line mixed with binary partially matches valid utf8: Ï€ is à93.1593

\ No newline at end of file
diff --git a/Tests/SubProject/CMakeLists.txt b/Tests/SubProject/CMakeLists.txt
index b669621..b2bada9 100644
--- a/Tests/SubProject/CMakeLists.txt
+++ b/Tests/SubProject/CMakeLists.txt
@@ -1,6 +1,15 @@
 cmake_minimum_required (VERSION 2.6)
 project(SubProject)
-message("${CMAKE_IMPORT_LIBRARY_SUFFIX}")
+file(REMOVE ${CMAKE_CURRENT_BINARY_DIR}/gen.cxx) # require generation
+add_custom_command(
+  OUTPUT gen.cxx
+  DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/gen.cxx.in
+  COMMAND ${CMAKE_COMMAND} -E copy
+             ${CMAKE_CURRENT_SOURCE_DIR}/gen.cxx.in gen.cxx
+  )
+add_custom_target(gen DEPENDS gen.cxx)
 add_library(bar bar.cxx)
+target_include_directories(bar PRIVATE ${CMAKE_CURRENT_BINARY_DIR})
+add_dependencies(bar gen)
 add_executable(car car.cxx)
 add_subdirectory(foo)
diff --git a/Tests/SubProject/bar.cxx b/Tests/SubProject/bar.cxx
index c3f6a18..c8b8743 100644
--- a/Tests/SubProject/bar.cxx
+++ b/Tests/SubProject/bar.cxx
@@ -1,4 +1 @@
-int bar()
-{
-  return 10;
-}
+#include "gen.cxx"
diff --git a/Tests/SubProject/gen.cxx.in b/Tests/SubProject/gen.cxx.in
new file mode 100644
index 0000000..c3f6a18
--- /dev/null
+++ b/Tests/SubProject/gen.cxx.in
@@ -0,0 +1,4 @@
+int bar()
+{
+  return 10;
+}
diff --git a/Tests/VSExternalInclude/CMakeLists.txt b/Tests/VSExternalInclude/CMakeLists.txt
index 8fc2871..73ea05a 100644
--- a/Tests/VSExternalInclude/CMakeLists.txt
+++ b/Tests/VSExternalInclude/CMakeLists.txt
@@ -6,7 +6,7 @@
 else()
   set(PROJECT_EXT vcproj)
 endif()
-if(${CMAKE_GENERATOR} MATCHES "Visual Studio 1[012]")
+if(${CMAKE_GENERATOR} MATCHES "Visual Studio 1[0124]")
   set(PROJECT_EXT vcxproj)
 endif()
 
@@ -19,7 +19,9 @@
 
 # generate lib1
 execute_process(
-  COMMAND ${CMAKE_COMMAND} -G "${CMAKE_GENERATOR}" -T "${CMAKE_GENERATOR_TOOLSET}" "${VSExternalInclude_SOURCE_DIR}/Lib1"
+  COMMAND ${CMAKE_COMMAND} -G "${CMAKE_GENERATOR}"
+    -A "${CMAKE_GENERATOR_PLATFORM}"
+    -T "${CMAKE_GENERATOR_TOOLSET}" "${VSExternalInclude_SOURCE_DIR}/Lib1"
   WORKING_DIRECTORY ${LIB1_BINARY_DIR}
   OUTPUT_VARIABLE OUT
   ERROR_VARIABLE OUT
@@ -28,7 +30,9 @@
 
 # generate lib2
 execute_process(
-  COMMAND ${CMAKE_COMMAND} -G "${CMAKE_GENERATOR}" -T "${CMAKE_GENERATOR_TOOLSET}" "${VSExternalInclude_SOURCE_DIR}/Lib2"
+  COMMAND ${CMAKE_COMMAND} -G "${CMAKE_GENERATOR}"
+    -A "${CMAKE_GENERATOR_PLATFORM}"
+    -T "${CMAKE_GENERATOR_TOOLSET}" "${VSExternalInclude_SOURCE_DIR}/Lib2"
   WORKING_DIRECTORY ${LIB2_BINARY_DIR}
   OUTPUT_VARIABLE OUT
   ERROR_VARIABLE OUT
@@ -54,7 +58,7 @@
 # and the sln file can no longer be the only source
 # of that depend.  So, for VS 10 make the executable
 # depend on lib1 and lib2
-if(${CMAKE_GENERATOR} MATCHES "Visual Studio 1[012]")
+if(${CMAKE_GENERATOR} MATCHES "Visual Studio 1[0124]")
   add_dependencies(VSExternalInclude lib1)
 endif()
 
diff --git a/Tests/VSMASM/CMakeLists.txt b/Tests/VSMASM/CMakeLists.txt
new file mode 100644
index 0000000..f2570a3
--- /dev/null
+++ b/Tests/VSMASM/CMakeLists.txt
@@ -0,0 +1,10 @@
+cmake_minimum_required(VERSION 2.8.12)
+project(VSMASM C ASM_MASM)
+if(CMAKE_SIZEOF_VOID_P EQUAL 8)
+  add_definitions(-DTESTx64)
+else()
+  add_definitions(-DTESTi386)
+  set(CMAKE_ASM_MASM_FLAGS "${CMAKE_ASM_MASM_FLAGS} /safeseh")
+endif()
+include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include)
+add_executable(VSMASM main.c foo.asm)
diff --git a/Tests/VSMASM/foo.asm b/Tests/VSMASM/foo.asm
new file mode 100644
index 0000000..51cb969
--- /dev/null
+++ b/Tests/VSMASM/foo.asm
@@ -0,0 +1,7 @@
+ifndef TESTx64
+.386
+.model flat, c
+endif
+.code
+include <foo-proc.asm>
+end
diff --git a/Tests/VSMASM/include/foo-proc.asm b/Tests/VSMASM/include/foo-proc.asm
new file mode 100644
index 0000000..e8ba5dc
--- /dev/null
+++ b/Tests/VSMASM/include/foo-proc.asm
@@ -0,0 +1,4 @@
+foo proc public
+  mov eax,0
+  ret
+foo endp
diff --git a/Tests/VSMASM/main.c b/Tests/VSMASM/main.c
new file mode 100644
index 0000000..570ba16
--- /dev/null
+++ b/Tests/VSMASM/main.c
@@ -0,0 +1,2 @@
+extern int foo(void);
+int main(void) { return foo(); }
diff --git a/Tests/VSNsightTegra/AndroidManifest.xml b/Tests/VSNsightTegra/AndroidManifest.xml
new file mode 100644
index 0000000..951e8f3
--- /dev/null
+++ b/Tests/VSNsightTegra/AndroidManifest.xml
@@ -0,0 +1,16 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+      package="com.example.twolibs"
+      android:versionCode="1"
+      android:versionName="1.0">
+    <uses-sdk android:minSdkVersion="3" />
+    <application android:label="@string/app_name">
+        <activity android:name=".TwoLibs"
+                  android:label="@string/app_name">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+    </application>
+</manifest>
diff --git a/Tests/VSNsightTegra/CMakeLists.txt b/Tests/VSNsightTegra/CMakeLists.txt
new file mode 100644
index 0000000..570733b
--- /dev/null
+++ b/Tests/VSNsightTegra/CMakeLists.txt
@@ -0,0 +1,39 @@
+cmake_minimum_required(VERSION 3.0)
+project(VSNsightTegra C CXX)
+
+set(CMAKE_ANDROID_API 15)
+set(CMAKE_ANDROID_GUI 1)
+
+set(FIRST_C_FILES
+  jni/first.c
+  jni/first.h
+  )
+
+source_group(jni FILES ${FIRST_C_FILES})
+add_library(twolib-first ${FIRST_C_FILES})
+
+set(SECOND_C_FILES
+  jni/second.c
+  )
+set(SECOND_JAVA_FILES
+  src/com/example/twolibs/TwoLibs.java
+  )
+set(SECOND_RES_FILES
+  res/values/strings.xml
+  )
+set(SECOND_ANDROID_FILES
+  AndroidManifest.xml
+  )
+
+source_group(jni FILES ${SECOND_C_FILES})
+source_group(res\\values FILES ${SECOND_RES_FILES})
+source_group(src\\com\\example\\twolibs FILES ${SECOND_JAVA_FILES})
+add_executable(twolib-second
+  ${SECOND_C_FILES}
+  ${SECOND_JAVA_FILES}
+  ${SECOND_RES_FILES}
+  ${SECOND_ANDROID_FILES}
+  )
+target_include_directories(twolib-second PUBLIC jni)
+target_link_libraries(twolib-second twolib-first)
+target_link_libraries(twolib-second m) # test linking to library by name
diff --git a/Tests/VSNsightTegra/build.xml b/Tests/VSNsightTegra/build.xml
new file mode 100644
index 0000000..17a2cc0
--- /dev/null
+++ b/Tests/VSNsightTegra/build.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project name="TwoLibs" default="help">
+  <import file="${sdk.dir}/tools/ant/build.xml" />
+</project>
diff --git a/Tests/VSNsightTegra/jni/first.c b/Tests/VSNsightTegra/jni/first.c
new file mode 100644
index 0000000..f09e376
--- /dev/null
+++ b/Tests/VSNsightTegra/jni/first.c
@@ -0,0 +1,22 @@
+/*
+ * Copyright (C) 2009 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+#include "first.h"
+
+int  first(int  x, int  y)
+{
+    return x + y;
+}
diff --git a/Tests/VSNsightTegra/jni/first.h b/Tests/VSNsightTegra/jni/first.h
new file mode 100644
index 0000000..d893480
--- /dev/null
+++ b/Tests/VSNsightTegra/jni/first.h
@@ -0,0 +1,22 @@
+/*
+ * Copyright (C) 2009 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+#ifndef FIRST_H
+#define FIRST_H
+
+extern int first(int  x, int  y);
+
+#endif /* FIRST_H */
diff --git a/Tests/VSNsightTegra/jni/second.c b/Tests/VSNsightTegra/jni/second.c
new file mode 100644
index 0000000..4631848
--- /dev/null
+++ b/Tests/VSNsightTegra/jni/second.c
@@ -0,0 +1,27 @@
+/*
+ * Copyright (C) 2009 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+#include "first.h"
+#include <jni.h>
+
+jint
+Java_com_example_twolibs_TwoLibs_add( JNIEnv*  env,
+                                      jobject  this,
+                                      jint     x,
+                                      jint     y )
+{
+    return first(x, y);
+}
diff --git a/Tests/VSNsightTegra/res/values/strings.xml b/Tests/VSNsightTegra/res/values/strings.xml
new file mode 100644
index 0000000..858cdb4
--- /dev/null
+++ b/Tests/VSNsightTegra/res/values/strings.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+    <string name="app_name">TwoLibs</string>
+</resources>
diff --git a/Tests/VSNsightTegra/src/com/example/twolibs/TwoLibs.java b/Tests/VSNsightTegra/src/com/example/twolibs/TwoLibs.java
new file mode 100644
index 0000000..ef9da01
--- /dev/null
+++ b/Tests/VSNsightTegra/src/com/example/twolibs/TwoLibs.java
@@ -0,0 +1,46 @@
+/*
+ * Copyright (C) 2009 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.example.twolibs;
+
+import android.app.Activity;
+import android.widget.TextView;
+import android.os.Bundle;
+
+public class TwoLibs extends Activity
+{
+    /** Called when the activity is first created. */
+    @Override
+    public void onCreate(Bundle savedInstanceState)
+    {
+        super.onCreate(savedInstanceState);
+
+        TextView  tv = new TextView(this);
+        int       x  = 1000;
+        int       y  = 42;
+
+        // here, we dynamically load the library at runtime
+        // before calling the native method.
+        //
+        System.loadLibrary("twolib-second");
+
+        int  z = add(x, y);
+
+        tv.setText( "The sum of " + x + " and " + y + " is " + z );
+        setContentView(tv);
+    }
+
+    public native int add(int  x, int  y);
+}
diff --git a/Tests/VSResource/CMakeLists.txt b/Tests/VSResource/CMakeLists.txt
index c5cb336..17eb041 100644
--- a/Tests/VSResource/CMakeLists.txt
+++ b/Tests/VSResource/CMakeLists.txt
@@ -18,6 +18,11 @@
   message(STATUS "CMAKE_RC_COMPILER MATCHES windres")
   add_definitions(/DCMAKE_RCDEFINE=test.txt)
   add_definitions(/DCMAKE_RCDEFINE_NO_QUOTED_STRINGS)
+  if(MSYS AND CMAKE_CURRENT_BINARY_DIR MATCHES " ")
+    # windres cannot handle spaces in include dir, and
+    # for the MSys shell we do not convert to shortpath.
+    set(CMAKE_RC_NO_INCLUDE 1)
+  endif()
 elseif(MSVC60)
   # VS6 rc compiler does not deal well with spaces in a "/D" value, but it can
   # handle the quoting
@@ -30,10 +35,17 @@
   set(TEXTFILE_FROM_SOURCE_DIR "textfile, spaces in name, from binary dir")
   configure_file(${CMAKE_CURRENT_SOURCE_DIR}/test.txt
     "${CMAKE_CURRENT_BINARY_DIR}/test with spaces.txt" @ONLY)
-  include_directories(${CMAKE_CURRENT_BINARY_DIR})
   add_definitions(/DCMAKE_RCDEFINE="test with spaces.txt")
 endif()
 
+if(CMAKE_RC_NO_INCLUDE)
+  add_definitions(/DCMAKE_RC_NO_INCLUDE)
+else()
+  configure_file(${CMAKE_CURRENT_SOURCE_DIR}/include.rc.in
+    "${CMAKE_CURRENT_BINARY_DIR}/include.rc" @ONLY)
+  include_directories(${CMAKE_CURRENT_BINARY_DIR})
+endif()
+
 add_executable(VSResource main.cpp test.rc)
 
 set_property(TARGET VSResource
diff --git a/Tests/VSResource/include.rc.in b/Tests/VSResource/include.rc.in
new file mode 100644
index 0000000..f0f6859
--- /dev/null
+++ b/Tests/VSResource/include.rc.in
@@ -0,0 +1 @@
+// This file should be included.
diff --git a/Tests/VSResource/test.rc b/Tests/VSResource/test.rc
index 4ce4b53..0de4683 100644
--- a/Tests/VSResource/test.rc
+++ b/Tests/VSResource/test.rc
@@ -1,4 +1,7 @@
 #ifdef CMAKE_RCDEFINE
+# ifndef CMAKE_RC_NO_INCLUDE
+#  include <include.rc>
+# endif
 
 // This line can compile with either an unquoted or a quoted string
 1025 TEXTFILE CMAKE_RCDEFINE
diff --git a/Tests/VSWinStorePhone/CMakeLists.txt b/Tests/VSWinStorePhone/CMakeLists.txt
new file mode 100644
index 0000000..0041c75
--- /dev/null
+++ b/Tests/VSWinStorePhone/CMakeLists.txt
@@ -0,0 +1,114 @@
+cmake_minimum_required(VERSION 3.0)
+project(VSWinStorePhone)
+
+if(MSVC_VERSION GREATER 1700)
+  set(COMPILER_VERSION "12")
+elseif(MSVC_VERSION GREATER 1600)
+  set(COMPILER_VERSION "11")
+endif()
+
+set (APP_MANIFEST_NAME Package.appxmanifest)
+if("${CMAKE_SYSTEM_NAME}" STREQUAL "WindowsPhone")
+  set(PLATFORM WP)
+  add_definitions("-DPHONE")
+  if("${CMAKE_SYSTEM_VERSION}" STREQUAL "8.0")
+    set(APP_MANIFEST_NAME WMAppManifest.xml)
+    set(WINDOWS_PHONE8 1)
+  endif()
+elseif("${CMAKE_SYSTEM_NAME}" STREQUAL "WindowsStore")
+  set(PLATFORM STORE)
+else()
+  set(PLATFORM DESKTOP)
+  message(FATAL_ERROR "This app supports Store / Phone only. Please edit the target platform.")
+endif()
+
+set_property(GLOBAL PROPERTY USE_FOLDERS ON)
+
+set(EXE_NAME Direct3DApp1)
+set(SHORT_NAME ${EXE_NAME})
+set(PACKAGE_GUID "6514377e-dfd4-4cdb-80df-4e0366346efc")
+
+if (NOT "${PLATFORM}" STREQUAL "DESKTOP")
+  configure_file(
+    cmake/Package_vc${COMPILER_VERSION}.${PLATFORM}.appxmanifest.in
+    ${CMAKE_CURRENT_BINARY_DIR}/${APP_MANIFEST_NAME}
+    @ONLY)
+endif()
+
+set(SOURCE_FILES
+  Direct3DApp1/CubeRenderer.cpp
+  Direct3DApp1/Direct3DApp1.cpp
+  Direct3DApp1/Direct3DBase.cpp
+  Direct3DApp1/pch.cpp
+  )
+
+set(HEADER_FILES
+  Direct3DApp1/BasicTimer.h
+  Direct3DApp1/CubeRenderer.h
+  Direct3DApp1/Direct3DApp1.h
+  Direct3DApp1/Direct3DBase.h
+  Direct3DApp1/DirectXHelper.h
+  Direct3DApp1/pch.h
+  )
+
+set(PIXELSHADER_FILES
+  Direct3DApp1/SimplePixelShader.hlsl
+  )
+
+set(VERTEXSHADER_FILES
+  Direct3DApp1/SimpleVertexShader.hlsl
+  )
+
+set(CONTENT_FILES ${PIXELSHADER_FILES} ${VERTEXSHADER_FILES})
+
+if (WINDOWS_PHONE8)
+  set(CONTENT_FILES ${CONTENT_FILES}
+    ${CMAKE_CURRENT_BINARY_DIR}/${APP_MANIFEST_NAME}
+    Direct3DApp1/Assets/Tiles/FlipCycleTileLarge.png
+    Direct3DApp1/Assets/Tiles/FlipCycleTileMedium.png
+    Direct3DApp1/Assets/Tiles/FlipCycleTileSmall.png
+    Direct3DApp1/Assets/Tiles/IconicTileMediumLarge.png
+    Direct3DApp1/Assets/Tiles/IconicTileSmall.png
+    Direct3DApp1/Assets/ApplicationIcon.png
+    )
+  # Windows Phone 8.0 needs to copy all the images.
+  # It doesn't know to use relative paths.
+  file(COPY
+    Direct3DApp1/Assets/Tiles/FlipCycleTileLarge.png
+    Direct3DApp1/Assets/Tiles/FlipCycleTileMedium.png
+    Direct3DApp1/Assets/Tiles/FlipCycleTileSmall.png
+    Direct3DApp1/Assets/Tiles/IconicTileMediumLarge.png
+    Direct3DApp1/Assets/Tiles/IconicTileSmall.png
+    Direct3DApp1/Assets/ApplicationIcon.png
+    DESTINATION ${CMAKE_CURRENT_BINARY_DIR}
+    )
+
+elseif (NOT "${PLATFORM}" STREQUAL "DESKTOP")
+  set(CONTENT_FILES ${CONTENT_FILES}
+    ${CMAKE_CURRENT_BINARY_DIR}/${APP_MANIFEST_NAME}
+    Direct3DApp1/Assets/Logo.png
+    Direct3DApp1/Assets/SmallLogo.png
+    Direct3DApp1/Assets/SplashScreen.png
+    Direct3DApp1/Assets/StoreLogo.png
+    )
+endif()
+
+set(RESOURCE_FILES
+  ${CONTENT_FILES} ${DEBUG_CONTENT_FILES} ${RELEASE_CONTENT_FILES}
+  Direct3DApp1/Direct3DApp1_TemporaryKey.pfx)
+
+set_property(SOURCE ${CONTENT_FILES} PROPERTY VS_DEPLOYMENT_CONTENT 1)
+set_property(SOURCE ${DEBUG_CONTENT_FILES} PROPERTY VS_DEPLOYMENT_CONTENT $<CONFIG:Debug>)
+set_property(SOURCE ${RELEASE_CONTENT_FILES} PROPERTY
+  VS_DEPLOYMENT_CONTENT $<OR:$<CONFIG:Release>,$<CONFIG:RelWithDebInfo>,$<CONFIG:MinSizeRel>>)
+
+set_property(SOURCE ${PIXELSHADER_FILES} PROPERTY VS_SHADER_TYPE Pixel)
+set_property(SOURCE ${VERTEXSHADER_FILES} PROPERTY VS_SHADER_TYPE Vertex)
+
+source_group("Source Files" FILES ${SOURCE_FILES})
+source_group("Header Files" FILES ${HEADER_FILES})
+source_group("Resource Files" FILES ${RESOURCE_FILES})
+
+add_executable(${EXE_NAME} WIN32 ${SOURCE_FILES} ${HEADER_FILES} ${RESOURCE_FILES})
+set_property(TARGET ${EXE_NAME} PROPERTY VS_WINRT_COMPONENT TRUE)
+target_link_libraries(${EXE_NAME} d3d11)
diff --git a/Tests/VSWinStorePhone/Direct3DApp1/Assets/ApplicationIcon.png b/Tests/VSWinStorePhone/Direct3DApp1/Assets/ApplicationIcon.png
new file mode 100644
index 0000000..7d95d4e
--- /dev/null
+++ b/Tests/VSWinStorePhone/Direct3DApp1/Assets/ApplicationIcon.png
Binary files differ
diff --git a/Tests/VSWinStorePhone/Direct3DApp1/Assets/Logo.png b/Tests/VSWinStorePhone/Direct3DApp1/Assets/Logo.png
new file mode 100644
index 0000000..e26771c
--- /dev/null
+++ b/Tests/VSWinStorePhone/Direct3DApp1/Assets/Logo.png
Binary files differ
diff --git a/Tests/VSWinStorePhone/Direct3DApp1/Assets/SmallLogo.png b/Tests/VSWinStorePhone/Direct3DApp1/Assets/SmallLogo.png
new file mode 100644
index 0000000..1eb0d9d
--- /dev/null
+++ b/Tests/VSWinStorePhone/Direct3DApp1/Assets/SmallLogo.png
Binary files differ
diff --git a/Tests/VSWinStorePhone/Direct3DApp1/Assets/SplashScreen.png b/Tests/VSWinStorePhone/Direct3DApp1/Assets/SplashScreen.png
new file mode 100644
index 0000000..c951e03
--- /dev/null
+++ b/Tests/VSWinStorePhone/Direct3DApp1/Assets/SplashScreen.png
Binary files differ
diff --git a/Tests/VSWinStorePhone/Direct3DApp1/Assets/StoreLogo.png b/Tests/VSWinStorePhone/Direct3DApp1/Assets/StoreLogo.png
new file mode 100644
index 0000000..dcb6727
--- /dev/null
+++ b/Tests/VSWinStorePhone/Direct3DApp1/Assets/StoreLogo.png
Binary files differ
diff --git a/Tests/VSWinStorePhone/Direct3DApp1/Assets/Tiles/FlipCycleTileLarge.png b/Tests/VSWinStorePhone/Direct3DApp1/Assets/Tiles/FlipCycleTileLarge.png
new file mode 100644
index 0000000..e0c59ac
--- /dev/null
+++ b/Tests/VSWinStorePhone/Direct3DApp1/Assets/Tiles/FlipCycleTileLarge.png
Binary files differ
diff --git a/Tests/VSWinStorePhone/Direct3DApp1/Assets/Tiles/FlipCycleTileMedium.png b/Tests/VSWinStorePhone/Direct3DApp1/Assets/Tiles/FlipCycleTileMedium.png
new file mode 100644
index 0000000..e93b89d
--- /dev/null
+++ b/Tests/VSWinStorePhone/Direct3DApp1/Assets/Tiles/FlipCycleTileMedium.png
Binary files differ
diff --git a/Tests/VSWinStorePhone/Direct3DApp1/Assets/Tiles/FlipCycleTileSmall.png b/Tests/VSWinStorePhone/Direct3DApp1/Assets/Tiles/FlipCycleTileSmall.png
new file mode 100644
index 0000000..550b1b5
--- /dev/null
+++ b/Tests/VSWinStorePhone/Direct3DApp1/Assets/Tiles/FlipCycleTileSmall.png
Binary files differ
diff --git a/Tests/VSWinStorePhone/Direct3DApp1/Assets/Tiles/IconicTileMediumLarge.png b/Tests/VSWinStorePhone/Direct3DApp1/Assets/Tiles/IconicTileMediumLarge.png
new file mode 100644
index 0000000..686e6b5
--- /dev/null
+++ b/Tests/VSWinStorePhone/Direct3DApp1/Assets/Tiles/IconicTileMediumLarge.png
Binary files differ
diff --git a/Tests/VSWinStorePhone/Direct3DApp1/Assets/Tiles/IconicTileSmall.png b/Tests/VSWinStorePhone/Direct3DApp1/Assets/Tiles/IconicTileSmall.png
new file mode 100644
index 0000000..d4b5ede
--- /dev/null
+++ b/Tests/VSWinStorePhone/Direct3DApp1/Assets/Tiles/IconicTileSmall.png
Binary files differ
diff --git a/Tests/VSWinStorePhone/Direct3DApp1/BasicTimer.h b/Tests/VSWinStorePhone/Direct3DApp1/BasicTimer.h
new file mode 100644
index 0000000..b58c77d
--- /dev/null
+++ b/Tests/VSWinStorePhone/Direct3DApp1/BasicTimer.h
@@ -0,0 +1,76 @@
+#pragma once
+
+#include <wrl.h>
+
+// Helper class for basic timing.
+ref class BasicTimer sealed
+{
+public:
+  // Initializes internal timer values.
+  BasicTimer()
+  {
+    if (!QueryPerformanceFrequency(&m_frequency))
+    {
+      throw ref new Platform::FailureException();
+    }
+    Reset();
+  }
+
+  // Reset the timer to initial values.
+  void Reset()
+  {
+    Update();
+    m_startTime = m_currentTime;
+    m_total = 0.0f;
+    m_delta = 1.0f / 60.0f;
+  }
+
+  // Update the timer's internal values.
+  void Update()
+  {
+    if (!QueryPerformanceCounter(&m_currentTime))
+    {
+      throw ref new Platform::FailureException();
+    }
+
+    m_total = static_cast<float>(
+      static_cast<double>(m_currentTime.QuadPart - m_startTime.QuadPart) /
+      static_cast<double>(m_frequency.QuadPart)
+      );
+
+    if (m_lastTime.QuadPart == m_startTime.QuadPart)
+    {
+      // If the timer was just reset, report a time delta equivalent to 60Hz frame time.
+      m_delta = 1.0f / 60.0f;
+    }
+    else
+    {
+      m_delta = static_cast<float>(
+        static_cast<double>(m_currentTime.QuadPart - m_lastTime.QuadPart) /
+        static_cast<double>(m_frequency.QuadPart)
+        );
+    }
+
+    m_lastTime = m_currentTime;
+  }
+
+  // Duration in seconds between the last call to Reset() and the last call to Update().
+  property float Total
+  {
+    float get() { return m_total; }
+  }
+
+  // Duration in seconds between the previous two calls to Update().
+  property float Delta
+  {
+    float get() { return m_delta; }
+  }
+
+private:
+  LARGE_INTEGER m_frequency;
+  LARGE_INTEGER m_currentTime;
+  LARGE_INTEGER m_startTime;
+  LARGE_INTEGER m_lastTime;
+  float m_total;
+  float m_delta;
+};
diff --git a/Tests/VSWinStorePhone/Direct3DApp1/CubeRenderer.cpp b/Tests/VSWinStorePhone/Direct3DApp1/CubeRenderer.cpp
new file mode 100644
index 0000000..f4827f2
--- /dev/null
+++ b/Tests/VSWinStorePhone/Direct3DApp1/CubeRenderer.cpp
@@ -0,0 +1,260 @@
+#include "pch.h"
+#include "CubeRenderer.h"
+
+using namespace DirectX;
+using namespace Microsoft::WRL;
+using namespace Windows::Foundation;
+using namespace Windows::UI::Core;
+
+CubeRenderer::CubeRenderer() :
+  m_loadingComplete(false),
+  m_indexCount(0)
+{
+}
+
+void CubeRenderer::CreateDeviceResources()
+{
+  Direct3DBase::CreateDeviceResources();
+
+  auto loadVSTask = DX::ReadDataAsync("SimpleVertexShader.cso");
+  auto loadPSTask = DX::ReadDataAsync("SimplePixelShader.cso");
+
+  auto createVSTask = loadVSTask.then([this](Platform::Array<byte>^ fileData) {
+    DX::ThrowIfFailed(
+      m_d3dDevice->CreateVertexShader(
+        fileData->Data,
+        fileData->Length,
+        nullptr,
+        &m_vertexShader
+        )
+      );
+
+    const D3D11_INPUT_ELEMENT_DESC vertexDesc[] =
+    {
+      { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0,  D3D11_INPUT_PER_VERTEX_DATA, 0 },
+      { "COLOR",    0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
+    };
+
+    DX::ThrowIfFailed(
+      m_d3dDevice->CreateInputLayout(
+        vertexDesc,
+        ARRAYSIZE(vertexDesc),
+        fileData->Data,
+        fileData->Length,
+        &m_inputLayout
+        )
+      );
+  });
+
+  auto createPSTask = loadPSTask.then([this](Platform::Array<byte>^ fileData) {
+    DX::ThrowIfFailed(
+      m_d3dDevice->CreatePixelShader(
+        fileData->Data,
+        fileData->Length,
+        nullptr,
+        &m_pixelShader
+        )
+      );
+
+    CD3D11_BUFFER_DESC constantBufferDesc(sizeof(ModelViewProjectionConstantBuffer), D3D11_BIND_CONSTANT_BUFFER);
+    DX::ThrowIfFailed(
+      m_d3dDevice->CreateBuffer(
+        &constantBufferDesc,
+        nullptr,
+        &m_constantBuffer
+        )
+      );
+  });
+
+  auto createCubeTask = (createPSTask && createVSTask).then([this] () {
+    VertexPositionColor cubeVertices[] =
+    {
+      {XMFLOAT3(-0.5f, -0.5f, -0.5f), XMFLOAT3(0.0f, 0.0f, 0.0f)},
+      {XMFLOAT3(-0.5f, -0.5f,  0.5f), XMFLOAT3(0.0f, 0.0f, 1.0f)},
+      {XMFLOAT3(-0.5f,  0.5f, -0.5f), XMFLOAT3(0.0f, 1.0f, 0.0f)},
+      {XMFLOAT3(-0.5f,  0.5f,  0.5f), XMFLOAT3(0.0f, 1.0f, 1.0f)},
+      {XMFLOAT3( 0.5f, -0.5f, -0.5f), XMFLOAT3(1.0f, 0.0f, 0.0f)},
+      {XMFLOAT3( 0.5f, -0.5f,  0.5f), XMFLOAT3(1.0f, 0.0f, 1.0f)},
+      {XMFLOAT3( 0.5f,  0.5f, -0.5f), XMFLOAT3(1.0f, 1.0f, 0.0f)},
+      {XMFLOAT3( 0.5f,  0.5f,  0.5f), XMFLOAT3(1.0f, 1.0f, 1.0f)},
+    };
+
+    D3D11_SUBRESOURCE_DATA vertexBufferData = {0};
+    vertexBufferData.pSysMem = cubeVertices;
+    vertexBufferData.SysMemPitch = 0;
+    vertexBufferData.SysMemSlicePitch = 0;
+    CD3D11_BUFFER_DESC vertexBufferDesc(sizeof(cubeVertices), D3D11_BIND_VERTEX_BUFFER);
+    DX::ThrowIfFailed(
+      m_d3dDevice->CreateBuffer(
+        &vertexBufferDesc,
+        &vertexBufferData,
+        &m_vertexBuffer
+        )
+      );
+
+    unsigned short cubeIndices[] =
+    {
+      0,2,1, // -x
+      1,2,3,
+
+      4,5,6, // +x
+      5,7,6,
+
+      0,1,5, // -y
+      0,5,4,
+
+      2,6,7, // +y
+      2,7,3,
+
+      0,4,6, // -z
+      0,6,2,
+
+      1,3,7, // +z
+      1,7,5,
+    };
+
+    m_indexCount = ARRAYSIZE(cubeIndices);
+
+    D3D11_SUBRESOURCE_DATA indexBufferData = {0};
+    indexBufferData.pSysMem = cubeIndices;
+    indexBufferData.SysMemPitch = 0;
+    indexBufferData.SysMemSlicePitch = 0;
+    CD3D11_BUFFER_DESC indexBufferDesc(sizeof(cubeIndices), D3D11_BIND_INDEX_BUFFER);
+    DX::ThrowIfFailed(
+      m_d3dDevice->CreateBuffer(
+        &indexBufferDesc,
+        &indexBufferData,
+        &m_indexBuffer
+        )
+      );
+  });
+
+  createCubeTask.then([this] () {
+    m_loadingComplete = true;
+  });
+}
+
+void CubeRenderer::CreateWindowSizeDependentResources()
+{
+  Direct3DBase::CreateWindowSizeDependentResources();
+
+  float aspectRatio = m_windowBounds.Width / m_windowBounds.Height;
+  float fovAngleY = 70.0f * XM_PI / 180.0f;
+  if (aspectRatio < 1.0f)
+  {
+    fovAngleY /= aspectRatio;
+  }
+
+  // Note that the m_orientationTransform3D matrix is post-multiplied here
+  // in order to correctly orient the scene to match the display orientation.
+  // This post-multiplication step is required for any draw calls that are
+  // made to the swap chain render target. For draw calls to other targets,
+  // this transform should not be applied.
+  XMStoreFloat4x4(
+    &m_constantBufferData.projection,
+    XMMatrixTranspose(
+      XMMatrixMultiply(
+        XMMatrixPerspectiveFovRH(
+          fovAngleY,
+          aspectRatio,
+          0.01f,
+          100.0f
+          ),
+        XMLoadFloat4x4(&m_orientationTransform3D)
+        )
+      )
+    );
+}
+
+void CubeRenderer::Update(float timeTotal, float timeDelta)
+{
+  (void) timeDelta; // Unused parameter.
+
+  XMVECTOR eye = XMVectorSet(0.0f, 0.7f, 1.5f, 0.0f);
+  XMVECTOR at = XMVectorSet(0.0f, -0.1f, 0.0f, 0.0f);
+  XMVECTOR up = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);
+
+  XMStoreFloat4x4(&m_constantBufferData.view, XMMatrixTranspose(XMMatrixLookAtRH(eye, at, up)));
+  XMStoreFloat4x4(&m_constantBufferData.model, XMMatrixTranspose(XMMatrixRotationY(timeTotal * XM_PIDIV4)));
+}
+
+void CubeRenderer::Render()
+{
+  const float midnightBlue[] = { 0.098f, 0.098f, 0.439f, 1.000f };
+  m_d3dContext->ClearRenderTargetView(
+    m_renderTargetView.Get(),
+    midnightBlue
+    );
+
+  m_d3dContext->ClearDepthStencilView(
+    m_depthStencilView.Get(),
+    D3D11_CLEAR_DEPTH,
+    1.0f,
+    0
+    );
+
+  // Only draw the cube once it is loaded (loading is asynchronous).
+  if (!m_loadingComplete)
+  {
+    return;
+  }
+
+  m_d3dContext->OMSetRenderTargets(
+    1,
+    m_renderTargetView.GetAddressOf(),
+    m_depthStencilView.Get()
+    );
+
+  m_d3dContext->UpdateSubresource(
+    m_constantBuffer.Get(),
+    0,
+    NULL,
+    &m_constantBufferData,
+    0,
+    0
+    );
+
+  UINT stride = sizeof(VertexPositionColor);
+  UINT offset = 0;
+  m_d3dContext->IASetVertexBuffers(
+    0,
+    1,
+    m_vertexBuffer.GetAddressOf(),
+    &stride,
+    &offset
+    );
+
+  m_d3dContext->IASetIndexBuffer(
+    m_indexBuffer.Get(),
+    DXGI_FORMAT_R16_UINT,
+    0
+    );
+
+  m_d3dContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
+
+  m_d3dContext->IASetInputLayout(m_inputLayout.Get());
+
+  m_d3dContext->VSSetShader(
+    m_vertexShader.Get(),
+    nullptr,
+    0
+    );
+
+  m_d3dContext->VSSetConstantBuffers(
+    0,
+    1,
+    m_constantBuffer.GetAddressOf()
+    );
+
+  m_d3dContext->PSSetShader(
+    m_pixelShader.Get(),
+    nullptr,
+    0
+    );
+
+  m_d3dContext->DrawIndexed(
+    m_indexCount,
+    0,
+    0
+    );
+}
diff --git a/Tests/VSWinStorePhone/Direct3DApp1/CubeRenderer.h b/Tests/VSWinStorePhone/Direct3DApp1/CubeRenderer.h
new file mode 100644
index 0000000..68cb188
--- /dev/null
+++ b/Tests/VSWinStorePhone/Direct3DApp1/CubeRenderer.h
@@ -0,0 +1,44 @@
+#pragma once
+
+#include "Direct3DBase.h"
+
+struct ModelViewProjectionConstantBuffer
+{
+  DirectX::XMFLOAT4X4 model;
+  DirectX::XMFLOAT4X4 view;
+  DirectX::XMFLOAT4X4 projection;
+};
+
+struct VertexPositionColor
+{
+  DirectX::XMFLOAT3 pos;
+  DirectX::XMFLOAT3 color;
+};
+
+// This class renders a simple spinning cube.
+ref class CubeRenderer sealed : public Direct3DBase
+{
+public:
+  CubeRenderer();
+
+  // Direct3DBase methods.
+  virtual void CreateDeviceResources() override;
+  virtual void CreateWindowSizeDependentResources() override;
+  virtual void Render() override;
+
+  // Method for updating time-dependent objects.
+  void Update(float timeTotal, float timeDelta);
+
+private:
+  bool m_loadingComplete;
+
+  Microsoft::WRL::ComPtr<ID3D11InputLayout> m_inputLayout;
+  Microsoft::WRL::ComPtr<ID3D11Buffer> m_vertexBuffer;
+  Microsoft::WRL::ComPtr<ID3D11Buffer> m_indexBuffer;
+  Microsoft::WRL::ComPtr<ID3D11VertexShader> m_vertexShader;
+  Microsoft::WRL::ComPtr<ID3D11PixelShader> m_pixelShader;
+  Microsoft::WRL::ComPtr<ID3D11Buffer> m_constantBuffer;
+
+  uint32 m_indexCount;
+  ModelViewProjectionConstantBuffer m_constantBufferData;
+};
diff --git a/Tests/VSWinStorePhone/Direct3DApp1/Direct3DApp1.cpp b/Tests/VSWinStorePhone/Direct3DApp1/Direct3DApp1.cpp
new file mode 100644
index 0000000..3dbb97f
--- /dev/null
+++ b/Tests/VSWinStorePhone/Direct3DApp1/Direct3DApp1.cpp
@@ -0,0 +1,153 @@
+#include "pch.h"
+#include "Direct3DApp1.h"
+#include "BasicTimer.h"
+
+using namespace Windows::ApplicationModel;
+using namespace Windows::ApplicationModel::Core;
+using namespace Windows::ApplicationModel::Activation;
+using namespace Windows::UI::Core;
+using namespace Windows::System;
+using namespace Windows::Foundation;
+using namespace Windows::Graphics::Display;
+using namespace concurrency;
+
+Direct3DApp1::Direct3DApp1() :
+  m_windowClosed(false),
+  m_windowVisible(true)
+{
+}
+
+void Direct3DApp1::Initialize(CoreApplicationView^ applicationView)
+{
+  applicationView->Activated +=
+        ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &Direct3DApp1::OnActivated);
+
+  CoreApplication::Suspending +=
+        ref new EventHandler<SuspendingEventArgs^>(this, &Direct3DApp1::OnSuspending);
+
+  CoreApplication::Resuming +=
+        ref new EventHandler<Platform::Object^>(this, &Direct3DApp1::OnResuming);
+
+  m_renderer = ref new CubeRenderer();
+}
+
+void Direct3DApp1::SetWindow(CoreWindow^ window)
+{
+  window->SizeChanged +=
+        ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(this, &Direct3DApp1::OnWindowSizeChanged);
+
+  window->VisibilityChanged +=
+    ref new TypedEventHandler<CoreWindow^, VisibilityChangedEventArgs^>(this, &Direct3DApp1::OnVisibilityChanged);
+
+  window->Closed +=
+        ref new TypedEventHandler<CoreWindow^, CoreWindowEventArgs^>(this, &Direct3DApp1::OnWindowClosed);
+
+#ifndef PHONE
+  window->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0);
+#endif
+
+  window->PointerPressed +=
+    ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &Direct3DApp1::OnPointerPressed);
+
+  window->PointerMoved +=
+    ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &Direct3DApp1::OnPointerMoved);
+
+  m_renderer->Initialize(CoreWindow::GetForCurrentThread());
+}
+
+void Direct3DApp1::Load(Platform::String^ entryPoint)
+{
+}
+
+void Direct3DApp1::Run()
+{
+  BasicTimer^ timer = ref new BasicTimer();
+
+  while (!m_windowClosed)
+  {
+    if (m_windowVisible)
+    {
+      timer->Update();
+      CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);
+      m_renderer->Update(timer->Total, timer->Delta);
+      m_renderer->Render();
+      m_renderer->Present(); // This call is synchronized to the display frame rate.
+    }
+    else
+    {
+      CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessOneAndAllPending);
+    }
+  }
+}
+
+void Direct3DApp1::Uninitialize()
+{
+}
+
+void Direct3DApp1::OnWindowSizeChanged(CoreWindow^ sender, WindowSizeChangedEventArgs^ args)
+{
+  m_renderer->UpdateForWindowSizeChange();
+}
+
+void Direct3DApp1::OnVisibilityChanged(CoreWindow^ sender, VisibilityChangedEventArgs^ args)
+{
+  m_windowVisible = args->Visible;
+}
+
+void Direct3DApp1::OnWindowClosed(CoreWindow^ sender, CoreWindowEventArgs^ args)
+{
+  m_windowClosed = true;
+}
+
+void Direct3DApp1::OnPointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
+{
+  // Insert your code here.
+}
+
+void Direct3DApp1::OnPointerMoved(CoreWindow^ sender, PointerEventArgs^ args)
+{
+  // Insert your code here.
+}
+
+void Direct3DApp1::OnActivated(CoreApplicationView^ applicationView, IActivatedEventArgs^ args)
+{
+  CoreWindow::GetForCurrentThread()->Activate();
+}
+
+void Direct3DApp1::OnSuspending(Platform::Object^ sender, SuspendingEventArgs^ args)
+{
+  // Save app state asynchronously after requesting a deferral. Holding a deferral
+  // indicates that the application is busy performing suspending operations. Be
+  // aware that a deferral may not be held indefinitely. After about five seconds,
+  // the app will be forced to exit.
+  SuspendingDeferral^ deferral = args->SuspendingOperation->GetDeferral();
+  m_renderer->ReleaseResourcesForSuspending();
+
+  create_task([this, deferral]()
+  {
+    // Insert your code here.
+
+    deferral->Complete();
+  });
+}
+
+void Direct3DApp1::OnResuming(Platform::Object^ sender, Platform::Object^ args)
+{
+  // Restore any data or state that was unloaded on suspend. By default, data
+  // and state are persisted when resuming from suspend. Note that this event
+  // does not occur if the app was previously terminated.
+  m_renderer->CreateWindowSizeDependentResources();
+}
+
+IFrameworkView^ Direct3DApplicationSource::CreateView()
+{
+    return ref new Direct3DApp1();
+}
+
+[Platform::MTAThread]
+int main(Platform::Array<Platform::String^>^)
+{
+  auto direct3DApplicationSource = ref new Direct3DApplicationSource();
+  CoreApplication::Run(direct3DApplicationSource);
+  return 0;
+}
diff --git a/Tests/VSWinStorePhone/Direct3DApp1/Direct3DApp1.h b/Tests/VSWinStorePhone/Direct3DApp1/Direct3DApp1.h
new file mode 100644
index 0000000..40b69a1
--- /dev/null
+++ b/Tests/VSWinStorePhone/Direct3DApp1/Direct3DApp1.h
@@ -0,0 +1,40 @@
+#pragma once
+
+#include "pch.h"
+#include "CubeRenderer.h"
+
+ref class Direct3DApp1 sealed : public Windows::ApplicationModel::Core::IFrameworkView
+{
+public:
+  Direct3DApp1();
+
+  // IFrameworkView Methods.
+  virtual void Initialize(Windows::ApplicationModel::Core::CoreApplicationView^ applicationView);
+  virtual void SetWindow(Windows::UI::Core::CoreWindow^ window);
+  virtual void Load(Platform::String^ entryPoint);
+  virtual void Run();
+  virtual void Uninitialize();
+
+protected:
+  // Event Handlers.
+  void OnWindowSizeChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ args);
+  void OnLogicalDpiChanged(Platform::Object^ sender);
+  void OnActivated(Windows::ApplicationModel::Core::CoreApplicationView^ applicationView, Windows::ApplicationModel::Activation::IActivatedEventArgs^ args);
+  void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ args);
+  void OnResuming(Platform::Object^ sender, Platform::Object^ args);
+  void OnWindowClosed(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::CoreWindowEventArgs^ args);
+  void OnVisibilityChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ args);
+  void OnPointerPressed(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::PointerEventArgs^ args);
+  void OnPointerMoved(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::PointerEventArgs^ args);
+
+private:
+  CubeRenderer^ m_renderer;
+  bool m_windowClosed;
+  bool m_windowVisible;
+};
+
+ref class Direct3DApplicationSource sealed : Windows::ApplicationModel::Core::IFrameworkViewSource
+{
+public:
+  virtual Windows::ApplicationModel::Core::IFrameworkView^ CreateView();
+};
diff --git a/Tests/VSWinStorePhone/Direct3DApp1/Direct3DApp1_TemporaryKey.pfx b/Tests/VSWinStorePhone/Direct3DApp1/Direct3DApp1_TemporaryKey.pfx
new file mode 100644
index 0000000..1cad999
--- /dev/null
+++ b/Tests/VSWinStorePhone/Direct3DApp1/Direct3DApp1_TemporaryKey.pfx
Binary files differ
diff --git a/Tests/VSWinStorePhone/Direct3DApp1/Direct3DBase.cpp b/Tests/VSWinStorePhone/Direct3DApp1/Direct3DBase.cpp
new file mode 100644
index 0000000..46727b5
--- /dev/null
+++ b/Tests/VSWinStorePhone/Direct3DApp1/Direct3DBase.cpp
@@ -0,0 +1,384 @@
+#include "pch.h"
+#include "Direct3DBase.h"
+
+using namespace DirectX;
+using namespace Microsoft::WRL;
+using namespace Windows::UI::Core;
+using namespace Windows::Foundation;
+using namespace Windows::Graphics::Display;
+
+// Constructor.
+Direct3DBase::Direct3DBase()
+{
+}
+
+// Initialize the Direct3D resources required to run.
+void Direct3DBase::Initialize(CoreWindow^ window)
+{
+  m_window = window;
+
+  CreateDeviceResources();
+  CreateWindowSizeDependentResources();
+}
+
+// Recreate all device resources and set them back to the current state.
+void Direct3DBase::HandleDeviceLost()
+{
+  // Reset these member variables to ensure that UpdateForWindowSizeChange recreates all resources.
+  m_windowBounds.Width = 0;
+  m_windowBounds.Height = 0;
+  m_swapChain = nullptr;
+
+  CreateDeviceResources();
+  UpdateForWindowSizeChange();
+}
+
+// These are the resources that depend on the device.
+void Direct3DBase::CreateDeviceResources()
+{
+  // This flag adds support for surfaces with a different color channel ordering
+  // than the API default. It is required for compatibility with Direct2D.
+  UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
+
+#if defined(_DEBUG)
+  // If the project is in a debug build, enable debugging via SDK Layers with this flag.
+  creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
+#endif
+
+  // This array defines the set of DirectX hardware feature levels this app will support.
+  // Note the ordering should be preserved.
+  // Don't forget to declare your application's minimum required feature level in its
+  // description.  All applications are assumed to support 9.1 unless otherwise stated.
+  D3D_FEATURE_LEVEL featureLevels[] =
+  {
+    D3D_FEATURE_LEVEL_11_1,
+    D3D_FEATURE_LEVEL_11_0,
+    D3D_FEATURE_LEVEL_10_1,
+    D3D_FEATURE_LEVEL_10_0,
+    D3D_FEATURE_LEVEL_9_3,
+    D3D_FEATURE_LEVEL_9_2,
+    D3D_FEATURE_LEVEL_9_1
+  };
+
+  // Create the Direct3D 11 API device object and a corresponding context.
+  ComPtr<ID3D11Device> device;
+  ComPtr<ID3D11DeviceContext> context;
+  DX::ThrowIfFailed(
+    D3D11CreateDevice(
+      nullptr, // Specify nullptr to use the default adapter.
+      D3D_DRIVER_TYPE_HARDWARE,
+      nullptr,
+      creationFlags, // Set set debug and Direct2D compatibility flags.
+      featureLevels, // List of feature levels this app can support.
+      ARRAYSIZE(featureLevels),
+      D3D11_SDK_VERSION, // Always set this to D3D11_SDK_VERSION for Windows Store apps.
+      &device, // Returns the Direct3D device created.
+      &m_featureLevel, // Returns feature level of device created.
+      &context // Returns the device immediate context.
+      )
+    );
+
+  // Get the Direct3D 11.1 API device and context interfaces.
+  DX::ThrowIfFailed(
+    device.As(&m_d3dDevice)
+    );
+
+  DX::ThrowIfFailed(
+    context.As(&m_d3dContext)
+    );
+}
+
+// Allocate all memory resources that change on a window SizeChanged event.
+void Direct3DBase::CreateWindowSizeDependentResources()
+{
+  // Store the window bounds so the next time we get a SizeChanged event we can
+  // avoid rebuilding everything if the size is identical.
+  m_windowBounds = m_window->Bounds;
+
+  // Calculate the necessary swap chain and render target size in pixels.
+  float windowWidth = ConvertDipsToPixels(m_windowBounds.Width);
+  float windowHeight = ConvertDipsToPixels(m_windowBounds.Height);
+
+  // The width and height of the swap chain must be based on the window's
+  // landscape-oriented width and height. If the window is in a portrait
+  // orientation, the dimensions must be reversed.
+#if WINVER > 0x0602
+  m_orientation = DisplayInformation::GetForCurrentView()->CurrentOrientation;
+#else
+#if PHONE
+  // WP8 doesn't support rotations so always make it landscape
+  m_orientation = DisplayOrientations::Landscape;
+#else
+  m_orientation = DisplayProperties::CurrentOrientation;
+#endif
+#endif
+  bool swapDimensions =
+    m_orientation == DisplayOrientations::Portrait ||
+    m_orientation == DisplayOrientations::PortraitFlipped;
+  m_renderTargetSize.Width = swapDimensions ? windowHeight : windowWidth;
+  m_renderTargetSize.Height = swapDimensions ? windowWidth : windowHeight;
+
+  if(m_swapChain != nullptr)
+  {
+    // If the swap chain already exists, resize it.
+    DX::ThrowIfFailed(
+      m_swapChain->ResizeBuffers(
+        2, // Double-buffered swap chain.
+        static_cast<UINT>(m_renderTargetSize.Width),
+        static_cast<UINT>(m_renderTargetSize.Height),
+        DXGI_FORMAT_B8G8R8A8_UNORM,
+        0
+        )
+      );
+  }
+  else
+  {
+    // Otherwise, create a new one using the same adapter as the existing Direct3D device.
+    DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0};
+    swapChainDesc.Width = static_cast<UINT>(m_renderTargetSize.Width); // Match the size of the window.
+    swapChainDesc.Height = static_cast<UINT>(m_renderTargetSize.Height);
+    swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; // This is the most common swap chain format.
+    swapChainDesc.Stereo = false;
+    swapChainDesc.SampleDesc.Count = 1; // Don't use multi-sampling.
+    swapChainDesc.SampleDesc.Quality = 0;
+    swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
+#if PHONE && WINVER <= 0x0602
+    swapChainDesc.BufferCount = 1; // Use double-buffering to minimize latency.
+    swapChainDesc.Scaling = DXGI_SCALING_STRETCH; // On phone, only stretch and aspect-ratio stretch scaling are allowed.
+    swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; // On phone, no swap effects are supported.
+#else
+    swapChainDesc.BufferCount = 2; // Use double-buffering to minimize latency.
+    swapChainDesc.Scaling = DXGI_SCALING_NONE;
+    swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // All Windows Store apps must use this SwapEffect.
+#endif
+    swapChainDesc.Flags = 0;
+
+    ComPtr<IDXGIDevice1>  dxgiDevice;
+    DX::ThrowIfFailed(
+      m_d3dDevice.As(&dxgiDevice)
+      );
+
+    ComPtr<IDXGIAdapter> dxgiAdapter;
+    DX::ThrowIfFailed(
+      dxgiDevice->GetAdapter(&dxgiAdapter)
+      );
+
+    ComPtr<IDXGIFactory2> dxgiFactory;
+    DX::ThrowIfFailed(
+      dxgiAdapter->GetParent(
+        __uuidof(IDXGIFactory2),
+        &dxgiFactory
+        )
+      );
+
+    Windows::UI::Core::CoreWindow^ window = m_window.Get();
+    DX::ThrowIfFailed(
+      dxgiFactory->CreateSwapChainForCoreWindow(
+        m_d3dDevice.Get(),
+        reinterpret_cast<IUnknown*>(window),
+        &swapChainDesc,
+        nullptr, // Allow on all displays.
+        &m_swapChain
+        )
+      );
+
+    // Ensure that DXGI does not queue more than one frame at a time. This both reduces latency and
+    // ensures that the application will only render after each VSync, minimizing power consumption.
+    DX::ThrowIfFailed(
+      dxgiDevice->SetMaximumFrameLatency(1)
+      );
+  }
+
+  // Set the proper orientation for the swap chain, and generate the
+  // 3D matrix transformation for rendering to the rotated swap chain.
+  DXGI_MODE_ROTATION rotation = DXGI_MODE_ROTATION_UNSPECIFIED;
+  switch (m_orientation)
+  {
+    case DisplayOrientations::Landscape:
+      rotation = DXGI_MODE_ROTATION_IDENTITY;
+      m_orientationTransform3D = XMFLOAT4X4( // 0-degree Z-rotation
+        1.0f, 0.0f, 0.0f, 0.0f,
+        0.0f, 1.0f, 0.0f, 0.0f,
+        0.0f, 0.0f, 1.0f, 0.0f,
+        0.0f, 0.0f, 0.0f, 1.0f
+        );
+      break;
+
+    case DisplayOrientations::Portrait:
+      rotation = DXGI_MODE_ROTATION_ROTATE270;
+      m_orientationTransform3D = XMFLOAT4X4( // 90-degree Z-rotation
+        0.0f, 1.0f, 0.0f, 0.0f,
+        -1.0f, 0.0f, 0.0f, 0.0f,
+        0.0f, 0.0f, 1.0f, 0.0f,
+        0.0f, 0.0f, 0.0f, 1.0f
+        );
+      break;
+
+    case DisplayOrientations::LandscapeFlipped:
+      rotation = DXGI_MODE_ROTATION_ROTATE180;
+      m_orientationTransform3D = XMFLOAT4X4( // 180-degree Z-rotation
+        -1.0f, 0.0f, 0.0f, 0.0f,
+        0.0f, -1.0f, 0.0f, 0.0f,
+        0.0f, 0.0f, 1.0f, 0.0f,
+        0.0f, 0.0f, 0.0f, 1.0f
+        );
+      break;
+
+    case DisplayOrientations::PortraitFlipped:
+      rotation = DXGI_MODE_ROTATION_ROTATE90;
+      m_orientationTransform3D = XMFLOAT4X4( // 270-degree Z-rotation
+        0.0f, -1.0f, 0.0f, 0.0f,
+        1.0f, 0.0f, 0.0f, 0.0f,
+        0.0f, 0.0f, 1.0f, 0.0f,
+        0.0f, 0.0f, 0.0f, 1.0f
+        );
+      break;
+
+    default:
+      throw ref new Platform::FailureException();
+  }
+
+#if !PHONE || WINVER > 0x0602
+  DX::ThrowIfFailed(
+    m_swapChain->SetRotation(rotation)
+    );
+#endif // !PHONE
+
+  // Create a render target view of the swap chain back buffer.
+  ComPtr<ID3D11Texture2D> backBuffer;
+  DX::ThrowIfFailed(
+    m_swapChain->GetBuffer(
+      0,
+      __uuidof(ID3D11Texture2D),
+      &backBuffer
+      )
+    );
+
+  DX::ThrowIfFailed(
+    m_d3dDevice->CreateRenderTargetView(
+      backBuffer.Get(),
+      nullptr,
+      &m_renderTargetView
+      )
+    );
+
+  // Create a depth stencil view.
+  CD3D11_TEXTURE2D_DESC depthStencilDesc(
+    DXGI_FORMAT_D24_UNORM_S8_UINT,
+    static_cast<UINT>(m_renderTargetSize.Width),
+    static_cast<UINT>(m_renderTargetSize.Height),
+    1,
+    1,
+    D3D11_BIND_DEPTH_STENCIL
+    );
+
+  ComPtr<ID3D11Texture2D> depthStencil;
+  DX::ThrowIfFailed(
+    m_d3dDevice->CreateTexture2D(
+      &depthStencilDesc,
+      nullptr,
+      &depthStencil
+      )
+    );
+
+  CD3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc(D3D11_DSV_DIMENSION_TEXTURE2D);
+  DX::ThrowIfFailed(
+    m_d3dDevice->CreateDepthStencilView(
+      depthStencil.Get(),
+      &depthStencilViewDesc,
+      &m_depthStencilView
+      )
+    );
+
+  // Set the rendering viewport to target the entire window.
+  CD3D11_VIEWPORT viewport(
+    0.0f,
+    0.0f,
+    m_renderTargetSize.Width,
+    m_renderTargetSize.Height
+    );
+
+  m_d3dContext->RSSetViewports(1, &viewport);
+}
+
+// This method is called in the event handler for the SizeChanged event.
+void Direct3DBase::UpdateForWindowSizeChange()
+{
+  if (m_window->Bounds.Width != m_windowBounds.Width ||
+    m_window->Bounds.Height != m_windowBounds.Height ||
+#if WINVER > 0x0602
+    m_orientation != DisplayInformation::GetForCurrentView()->CurrentOrientation)
+#else
+    m_orientation != DisplayProperties::CurrentOrientation)
+#endif
+  {
+    ID3D11RenderTargetView* nullViews[] = {nullptr};
+    m_d3dContext->OMSetRenderTargets(ARRAYSIZE(nullViews), nullViews, nullptr);
+    m_renderTargetView = nullptr;
+    m_depthStencilView = nullptr;
+    m_d3dContext->Flush();
+    CreateWindowSizeDependentResources();
+  }
+}
+
+void Direct3DBase::ReleaseResourcesForSuspending()
+{
+  // Phone applications operate in a memory-constrained environment, so when entering
+  // the background it is a good idea to free memory-intensive objects that will be
+  // easy to restore upon reactivation. The swapchain and backbuffer are good candidates
+  // here, as they consume a large amount of memory and can be reinitialized quickly.
+  m_swapChain = nullptr;
+  m_renderTargetView = nullptr;
+  m_depthStencilView = nullptr;
+}
+
+// Method to deliver the final image to the display.
+void Direct3DBase::Present()
+{
+  // The first argument instructs DXGI to block until VSync, putting the application
+  // to sleep until the next VSync. This ensures we don't waste any cycles rendering
+  // frames that will never be displayed to the screen.
+#if PHONE && WINVER <= 0x0602
+  HRESULT hr = m_swapChain->Present(1, 0);
+#else
+  // The application may optionally specify "dirty" or "scroll"
+  // rects to improve efficiency in certain scenarios.
+  DXGI_PRESENT_PARAMETERS parameters = { 0 };
+  parameters.DirtyRectsCount = 0;
+  parameters.pDirtyRects = nullptr;
+  parameters.pScrollRect = nullptr;
+  parameters.pScrollOffset = nullptr;
+
+  HRESULT hr = m_swapChain->Present1(1, 0 , &parameters);
+#endif
+
+  // Discard the contents of the render target.
+  // This is a valid operation only when the existing contents will be entirely
+  // overwritten. If dirty or scroll rects are used, this call should be removed.
+  m_d3dContext->DiscardView(m_renderTargetView.Get());
+
+  // Discard the contents of the depth stencil.
+  m_d3dContext->DiscardView(m_depthStencilView.Get());
+
+  // If the device was removed either by a disconnect or a driver upgrade, we
+  // must recreate all device resources.
+  if (hr == DXGI_ERROR_DEVICE_REMOVED)
+  {
+    HandleDeviceLost();
+  }
+  else
+  {
+    DX::ThrowIfFailed(hr);
+  }
+}
+
+// Method to convert a length in device-independent pixels (DIPs) to a length in physical pixels.
+float Direct3DBase::ConvertDipsToPixels(float dips)
+{
+  static const float dipsPerInch = 96.0f;
+#if WINVER > 0x0602
+  return floor(dips * DisplayInformation::GetForCurrentView()->LogicalDpi / dipsPerInch + 0.5f); // Round to nearest integer.
+#else
+  return floor(dips * DisplayProperties::LogicalDpi / dipsPerInch + 0.5f); // Round to nearest integer.
+#endif
+}
diff --git a/Tests/VSWinStorePhone/Direct3DApp1/Direct3DBase.h b/Tests/VSWinStorePhone/Direct3DApp1/Direct3DBase.h
new file mode 100644
index 0000000..bba9f16
--- /dev/null
+++ b/Tests/VSWinStorePhone/Direct3DApp1/Direct3DBase.h
@@ -0,0 +1,39 @@
+#pragma once
+
+#include "DirectXHelper.h"
+
+// Helper class that initializes DirectX APIs for 3D rendering.
+ref class Direct3DBase abstract
+{
+internal:
+  Direct3DBase();
+
+public:
+  virtual void Initialize(Windows::UI::Core::CoreWindow^ window);
+  virtual void HandleDeviceLost();
+  virtual void CreateDeviceResources();
+  virtual void CreateWindowSizeDependentResources();
+  virtual void UpdateForWindowSizeChange();
+  virtual void ReleaseResourcesForSuspending();
+  virtual void Render() = 0;
+  virtual void Present();
+  virtual float ConvertDipsToPixels(float dips);
+
+protected private:
+  // Direct3D Objects.
+  Microsoft::WRL::ComPtr<ID3D11Device1> m_d3dDevice;
+  Microsoft::WRL::ComPtr<ID3D11DeviceContext1> m_d3dContext;
+  Microsoft::WRL::ComPtr<IDXGISwapChain1> m_swapChain;
+  Microsoft::WRL::ComPtr<ID3D11RenderTargetView> m_renderTargetView;
+  Microsoft::WRL::ComPtr<ID3D11DepthStencilView> m_depthStencilView;
+
+  // Cached renderer properties.
+  D3D_FEATURE_LEVEL m_featureLevel;
+  Windows::Foundation::Size m_renderTargetSize;
+  Windows::Foundation::Rect m_windowBounds;
+  Platform::Agile<Windows::UI::Core::CoreWindow> m_window;
+  Windows::Graphics::Display::DisplayOrientations m_orientation;
+
+  // Transform used for display orientation.
+  DirectX::XMFLOAT4X4 m_orientationTransform3D;
+};
diff --git a/Tests/VSWinStorePhone/Direct3DApp1/DirectXHelper.h b/Tests/VSWinStorePhone/Direct3DApp1/DirectXHelper.h
new file mode 100644
index 0000000..d411a9b
--- /dev/null
+++ b/Tests/VSWinStorePhone/Direct3DApp1/DirectXHelper.h
@@ -0,0 +1,45 @@
+#pragma once
+
+#include <wrl/client.h>
+#include <ppl.h>
+#include <ppltasks.h>
+
+namespace DX
+{
+  inline void ThrowIfFailed(HRESULT hr)
+  {
+    if (FAILED(hr))
+    {
+      // Set a breakpoint on this line to catch Win32 API errors.
+      throw Platform::Exception::CreateException(hr);
+    }
+  }
+
+  // Function that reads from a binary file asynchronously.
+  inline Concurrency::task<Platform::Array<byte>^> ReadDataAsync(Platform::String^ filename)
+  {
+    using namespace Windows::Storage;
+    using namespace Concurrency;
+
+    auto folder = Windows::ApplicationModel::Package::Current->InstalledLocation;
+
+    return create_task(folder->GetFileAsync(filename)).then([] (StorageFile^ file)
+    {
+#if !PHONE
+      return FileIO::ReadBufferAsync(file);
+#else
+      return file->OpenReadAsync();
+    }).then([](Streams::IRandomAccessStreamWithContentType^ stream)
+    {
+      unsigned int bufferSize = static_cast<unsigned int>(stream->Size);
+      auto fileBuffer = ref new Streams::Buffer(bufferSize);
+      return stream->ReadAsync(fileBuffer, bufferSize, Streams::InputStreamOptions::None);
+#endif
+    }).then([] (Streams::IBuffer^ fileBuffer) -> Platform::Array<byte>^
+    {
+      auto fileData = ref new Platform::Array<byte>(fileBuffer->Length);
+      Streams::DataReader::FromBuffer(fileBuffer)->ReadBytes(fileData);
+      return fileData;
+    });
+  }
+}
diff --git a/Tests/VSWinStorePhone/Direct3DApp1/SimplePixelShader.cso b/Tests/VSWinStorePhone/Direct3DApp1/SimplePixelShader.cso
new file mode 100644
index 0000000..56f9c17
--- /dev/null
+++ b/Tests/VSWinStorePhone/Direct3DApp1/SimplePixelShader.cso
Binary files differ
diff --git a/Tests/VSWinStorePhone/Direct3DApp1/SimplePixelShader.hlsl b/Tests/VSWinStorePhone/Direct3DApp1/SimplePixelShader.hlsl
new file mode 100644
index 0000000..d61e2c8
--- /dev/null
+++ b/Tests/VSWinStorePhone/Direct3DApp1/SimplePixelShader.hlsl
@@ -0,0 +1,10 @@
+struct PixelShaderInput
+{
+  float4 pos : SV_POSITION;
+  float3 color : COLOR0;
+};
+
+float4 main(PixelShaderInput input) : SV_TARGET
+{
+  return float4(input.color,1.0f);
+}
diff --git a/Tests/VSWinStorePhone/Direct3DApp1/SimpleVertexShader.cso b/Tests/VSWinStorePhone/Direct3DApp1/SimpleVertexShader.cso
new file mode 100644
index 0000000..ea80258
--- /dev/null
+++ b/Tests/VSWinStorePhone/Direct3DApp1/SimpleVertexShader.cso
Binary files differ
diff --git a/Tests/VSWinStorePhone/Direct3DApp1/SimpleVertexShader.hlsl b/Tests/VSWinStorePhone/Direct3DApp1/SimpleVertexShader.hlsl
new file mode 100644
index 0000000..65d60e5
--- /dev/null
+++ b/Tests/VSWinStorePhone/Direct3DApp1/SimpleVertexShader.hlsl
@@ -0,0 +1,35 @@
+cbuffer ModelViewProjectionConstantBuffer : register(b0)
+{
+  matrix model;
+  matrix view;
+  matrix projection;
+};
+
+struct VertexShaderInput
+{
+  float3 pos : POSITION;
+  float3 color : COLOR0;
+};
+
+struct VertexShaderOutput
+{
+  float4 pos : SV_POSITION;
+  float3 color : COLOR0;
+};
+
+VertexShaderOutput main(VertexShaderInput input)
+{
+  VertexShaderOutput output;
+  float4 pos = float4(input.pos, 1.0f);
+
+  // Transform the vertex position into projected space.
+  pos = mul(pos, model);
+  pos = mul(pos, view);
+  pos = mul(pos, projection);
+  output.pos = pos;
+
+  // Pass through the color without modification.
+  output.color = input.color;
+
+  return output;
+}
diff --git a/Tests/VSWinStorePhone/Direct3DApp1/pch.cpp b/Tests/VSWinStorePhone/Direct3DApp1/pch.cpp
new file mode 100644
index 0000000..1d9f38c
--- /dev/null
+++ b/Tests/VSWinStorePhone/Direct3DApp1/pch.cpp
@@ -0,0 +1 @@
+#include "pch.h"
diff --git a/Tests/VSWinStorePhone/Direct3DApp1/pch.h b/Tests/VSWinStorePhone/Direct3DApp1/pch.h
new file mode 100644
index 0000000..2302e66
--- /dev/null
+++ b/Tests/VSWinStorePhone/Direct3DApp1/pch.h
@@ -0,0 +1,7 @@
+#pragma once
+
+#include <wrl/client.h>
+#include <d3d11_1.h>
+#include <DirectXMath.h>
+#include <memory>
+#include <agile.h>
diff --git a/Tests/VSWinStorePhone/cmake/Package_vc11.store.appxmanifest.in b/Tests/VSWinStorePhone/cmake/Package_vc11.store.appxmanifest.in
new file mode 100644
index 0000000..d3cb21f
--- /dev/null
+++ b/Tests/VSWinStorePhone/cmake/Package_vc11.store.appxmanifest.in
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Package xmlns="http://schemas.microsoft.com/appx/2010/manifest">
+  <Identity Name="@PACKAGE_GUID@" Publisher="CN=mgong" Version="1.0.0.0" />
+  <Properties>
+    <DisplayName>@SHORT_NAME@</DisplayName>
+    <PublisherDisplayName>mgong</PublisherDisplayName>
+    <Logo>StoreLogo.png</Logo>
+  </Properties>
+  <Prerequisites>
+    <OSMinVersion>6.2.1</OSMinVersion>
+    <OSMaxVersionTested>6.2.1</OSMaxVersionTested>
+  </Prerequisites>
+  <Resources>
+    <Resource Language="x-generate" />
+  </Resources>
+  <Applications>
+    <Application Id="App" Executable="$targetnametoken$.exe" EntryPoint="@SHORT_NAME@.App">
+      <VisualElements DisplayName="@SHORT_NAME@" Description="@SHORT_NAME@" BackgroundColor="#336699" ForegroundText="light" Logo="Logo.png" SmallLogo="SmallLogo.png">
+        <DefaultTile ShowName="allLogos" ShortName="@SHORT_NAME@" />
+        <SplashScreen Image="SplashScreen.png" />
+      </VisualElements>
+    </Application>
+  </Applications>
+</Package>
diff --git a/Tests/VSWinStorePhone/cmake/Package_vc11.wp.appxmanifest.in b/Tests/VSWinStorePhone/cmake/Package_vc11.wp.appxmanifest.in
new file mode 100644
index 0000000..70f3abf
--- /dev/null
+++ b/Tests/VSWinStorePhone/cmake/Package_vc11.wp.appxmanifest.in
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Deployment xmlns="http://schemas.microsoft.com/windowsphone/2012/deployment" AppPlatformVersion="8.0">
+  <DefaultLanguage xmlns="" code="en-US"/>
+  <App xmlns="" ProductID="{@PACKAGE_GUID@}" Title="@SHORT_NAME@" RuntimeType="Modern Native" Version="1.0.0.0" Genre="apps.normal"  Author="mgong" Description="Simple Direct3D application" Publisher="@SHORT_NAME@" PublisherID="{c618991e-1d39-41c2-a881-d3310705a091}">
+    <IconPath IsRelative="true" IsResource="false">ApplicationIcon.png</IconPath>
+    <Capabilities>
+      <Capability Name="ID_CAP_NETWORKING" />
+      <Capability Name="ID_CAP_MEDIALIB_AUDIO" />
+      <Capability Name="ID_CAP_MEDIALIB_PLAYBACK" />
+    </Capabilities>
+    <Tasks>
+      <DefaultTask Name="_default" ImagePath="@SHORT_NAME@.exe" ImageParams="" />
+    </Tasks>
+    <Tokens>
+      <PrimaryToken TokenID="@SHORT_NAME@Token" TaskName="_default">
+        <TemplateFlip>
+          <SmallImageURI IsRelative="true" IsResource="false">FlipCycleTileSmall.png</SmallImageURI>
+          <Count>0</Count>
+          <BackgroundImageURI IsRelative="true" IsResource="false">FlipCycleTileMedium.png</BackgroundImageURI>
+          <Title>@SHORT_NAME@</Title>
+          <BackContent></BackContent>
+          <BackBackgroundImageURI></BackBackgroundImageURI>
+          <BackTitle></BackTitle>
+          <DeviceLockImageURI></DeviceLockImageURI>
+          <HasLarge></HasLarge>
+        </TemplateFlip>
+      </PrimaryToken>
+    </Tokens>
+    <ScreenResolutions>
+      <ScreenResolution Name="ID_RESOLUTION_WVGA" />
+      <ScreenResolution Name="ID_RESOLUTION_WXGA" />
+      <ScreenResolution Name="ID_RESOLUTION_HD720P" />
+    </ScreenResolutions>
+  </App>
+</Deployment>
diff --git a/Tests/VSWinStorePhone/cmake/Package_vc12.store.appxmanifest.in b/Tests/VSWinStorePhone/cmake/Package_vc12.store.appxmanifest.in
new file mode 100644
index 0000000..495f18e
--- /dev/null
+++ b/Tests/VSWinStorePhone/cmake/Package_vc12.store.appxmanifest.in
@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Package xmlns="http://schemas.microsoft.com/appx/2010/manifest" xmlns:m2="http://schemas.microsoft.com/appx/2013/manifest">
+  <Identity Name="@PACKAGE_GUID@" Publisher="CN=mgong" Version="1.1.0.0" />
+  <Properties>
+    <DisplayName>@SHORT_NAME@</DisplayName>
+    <PublisherDisplayName>mgong</PublisherDisplayName>
+    <Logo>StoreLogo.png</Logo>
+  </Properties>
+  <Prerequisites>
+    <OSMinVersion>6.3</OSMinVersion>
+    <OSMaxVersionTested>6.3</OSMaxVersionTested>
+  </Prerequisites>
+  <Resources>
+    <Resource Language="x-generate" />
+  </Resources>
+  <Applications>
+    <Application Id="App" Executable="$targetnametoken$.exe" EntryPoint="@SHORT_NAME@.App">
+      <m2:VisualElements
+        DisplayName="@SHORT_NAME@"
+        Description="@SHORT_NAME@"
+        BackgroundColor="#336699"
+        ForegroundText="light"
+        Square150x150Logo="Logo.png"
+        Square30x30Logo="SmallLogo.png">
+        <m2:DefaultTile ShortName="@SHORT_NAME@">
+          <m2:ShowNameOnTiles>
+            <m2:ShowOn Tile="square150x150Logo" />
+          </m2:ShowNameOnTiles>
+        </m2:DefaultTile>
+        <m2:SplashScreen Image="SplashScreen.png" />
+      </m2:VisualElements>
+    </Application>
+  </Applications>
+</Package>
diff --git a/Tests/VSWinStorePhone/cmake/Package_vc12.wp.appxmanifest.in b/Tests/VSWinStorePhone/cmake/Package_vc12.wp.appxmanifest.in
new file mode 100644
index 0000000..2d4d389
--- /dev/null
+++ b/Tests/VSWinStorePhone/cmake/Package_vc12.wp.appxmanifest.in
@@ -0,0 +1,36 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Package xmlns="http://schemas.microsoft.com/appx/2010/manifest" xmlns:m2="http://schemas.microsoft.com/appx/2013/manifest" xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest">
+  <Identity Name="@PACKAGE_GUID@" Publisher="CN=mgong" Version="1.1.0.0" />
+  <mp:PhoneIdentity PhoneProductId="@PACKAGE_GUID@" PhonePublisherId="00000000-0000-0000-0000-000000000000"/>
+
+  <Properties>
+    <DisplayName>@SHORT_NAME@</DisplayName>
+    <PublisherDisplayName>mgong</PublisherDisplayName>
+    <Logo>StoreLogo.png</Logo>
+  </Properties>
+  <Prerequisites>
+    <OSMinVersion>6.3.1</OSMinVersion>
+    <OSMaxVersionTested>6.3.1</OSMaxVersionTested>
+  </Prerequisites>
+  <Resources>
+    <Resource Language="x-generate" />
+  </Resources>
+  <Applications>
+    <Application Id="App" Executable="$targetnametoken$.exe" EntryPoint="@SHORT_NAME@.App">
+      <m2:VisualElements
+        DisplayName="@SHORT_NAME@"
+        Description="@SHORT_NAME@"
+        BackgroundColor="#336699"
+        ForegroundText="light"
+        Square150x150Logo="Logo.png"
+        Square30x30Logo="SmallLogo.png">
+        <m2:DefaultTile ShortName="@SHORT_NAME@">
+          <m2:ShowNameOnTiles>
+            <m2:ShowOn Tile="square150x150Logo" />
+          </m2:ShowNameOnTiles>
+        </m2:DefaultTile>
+        <m2:SplashScreen Image="SplashScreen.png" />
+      </m2:VisualElements>
+    </Application>
+  </Applications>
+</Package>
diff --git a/Utilities/Doxygen/doxyfile.in b/Utilities/Doxygen/doxyfile.in
index 9743af7..2c131f5 100644
--- a/Utilities/Doxygen/doxyfile.in
+++ b/Utilities/Doxygen/doxyfile.in
@@ -6,6 +6,10 @@
 PROJECT_NAME         = CMake
 
 FULL_PATH_NAMES      = YES
+STRIP_FROM_PATH      = \
+ "@CMake_SOURCE_DIR@/Source/" \
+ "@CMake_BINARY_DIR@/Source/"
+
 WARN_IF_UNDOCUMENTED = NO
 
 GENERATE_TREEVIEW    = NO
@@ -40,6 +44,7 @@
 INPUT                = \
  "@CMake_SOURCE_DIR@/Source" \
  "@CMake_SOURCE_DIR@/Source/CPack" \
+ "@CMake_SOURCE_DIR@/Source/CPack/IFW" \
  "@CMake_SOURCE_DIR@/Source/CTest" \
  "@CMake_SOURCE_DIR@/Source/CursesDialog" \
  "@CMake_SOURCE_DIR@/Source/MFCDialog" \
diff --git a/Utilities/KWIML/ABI.h.in b/Utilities/KWIML/ABI.h.in
index b71cdfb..21c9139 100644
--- a/Utilities/KWIML/ABI.h.in
+++ b/Utilities/KWIML/ABI.h.in
@@ -398,6 +398,10 @@
 #elif defined(__mips) || defined(__mips__) || defined(__MIPS__)
 # define @KWIML@_ABI_ENDIAN_ID @KWIML@_ABI_ENDIAN_ID_BIG
 
+/* OpenRISC 1000 */
+#elif defined(__or1k__)
+# define @KWIML@_ABI_ENDIAN_ID @KWIML@_ABI_ENDIAN_ID_BIG
+
 /* RS/6000 */
 #elif defined(__THW_RS600) || defined(_IBMR2) || defined(_POWER)
 # define @KWIML@_ABI_ENDIAN_ID @KWIML@_ABI_ENDIAN_ID_BIG
diff --git a/Utilities/Release/dashmacmini2_release.cmake b/Utilities/Release/dashmacmini2_release.cmake
index 6a27119..ba82aab 100644
--- a/Utilities/Release/dashmacmini2_release.cmake
+++ b/Utilities/Release/dashmacmini2_release.cmake
@@ -6,6 +6,7 @@
 set(MAKE_PROGRAM "make")
 set(MAKE "${MAKE_PROGRAM} -j2")
 set(CPACK_BINARY_GENERATORS "DragNDrop TGZ TZ")
+set(CPACK_DMG_FORMAT "UDBZ") #build using bzip2 for smaller package size
 set(INITIAL_CACHE "
 CMAKE_BUILD_TYPE:STRING=Release
 CMAKE_OSX_ARCHITECTURES:STRING=ppc;i386
diff --git a/Utilities/Release/dashmacmini5_release.cmake b/Utilities/Release/dashmacmini5_release.cmake
index 16a30b3..6c9b8f4 100644
--- a/Utilities/Release/dashmacmini5_release.cmake
+++ b/Utilities/Release/dashmacmini5_release.cmake
@@ -7,13 +7,14 @@
 set(MAKE "${MAKE_PROGRAM} -j5")
 set(CPACK_BINARY_GENERATORS "DragNDrop TGZ TZ")
 set(CPACK_SOURCE_GENERATORS "TGZ TZ")
+set(CPACK_DMG_FORMAT "UDBZ") #build using bzip2 for smaller package size
 set(INITIAL_CACHE "
 CMAKE_USE_OPENSSL:BOOL=ON
 OPENSSL_CRYPTO_LIBRARY:FILEPATH=/Users/kitware/openssl-1.0.1g-install/lib/libcrypto.a
 OPENSSL_INCLUDE_DIR:PATH=/Users/kitware/openssl-1.0.1g-install/include
 OPENSSL_SSL_LIBRARY:FILEPATH=/Users/kitware/openssl-1.0.1g-install/lib/libssl.a
 CMAKE_BUILD_TYPE:STRING=Release
-CMAKE_OSX_ARCHITECTURES:STRING=x86_64;i386
+CMAKE_OSX_ARCHITECTURES:STRING=x86_64
 CMAKE_OSX_DEPLOYMENT_TARGET:STRING=10.5
 CMAKE_SKIP_BOOTSTRAP_TEST:STRING=TRUE
 CPACK_SYSTEM_NAME:STRING=Darwin64-universal
diff --git a/Utilities/Sphinx/CMakeLists.txt b/Utilities/Sphinx/CMakeLists.txt
index 951f7ab..a58604e 100644
--- a/Utilities/Sphinx/CMakeLists.txt
+++ b/Utilities/Sphinx/CMakeLists.txt
@@ -69,6 +69,8 @@
   list(APPEND doc_formats text)
 endif()
 if(SPHINX_QTHELP)
+  find_package(PythonInterp REQUIRED)
+
   find_program(QCOLLECTIONGENERATOR_EXECUTABLE
     NAMES qcollectiongenerator
     DOC "qcollectiongenerator tool"
@@ -88,7 +90,15 @@
     COMMAND ${CMAKE_COMMAND} "-DQTHELP_DIR=${CMAKE_CURRENT_BINARY_DIR}/qthelp/"
       "-DCMake_VERSION=${CMake_VERSION_MAJOR}${CMake_VERSION_MINOR}${CMake_VERSION_PATCH}"
       -P "${CMAKE_CURRENT_SOURCE_DIR}/fixup_qthelp_names.cmake"
-    COMMAND qcollectiongenerator ${CMAKE_CURRENT_BINARY_DIR}/qthelp/CMake.qhcp
+
+    # Create proper identifiers. Workaround for
+    # https://bitbucket.org/birkenfeld/sphinx/issue/1491/qthelp-should-generate-identifiers-for
+    COMMAND "${PYTHON_EXECUTABLE}"
+      "${CMAKE_CURRENT_SOURCE_DIR}/create_identifiers.py"
+      "${CMAKE_CURRENT_BINARY_DIR}/qthelp/"
+
+    COMMAND ${QCOLLECTIONGENERATOR_EXECUTABLE}
+      ${CMAKE_CURRENT_BINARY_DIR}/qthelp/CMake.qhcp
   )
 endif()
 
diff --git a/Utilities/Sphinx/create_identifiers.py b/Utilities/Sphinx/create_identifiers.py
new file mode 100755
index 0000000..7715e53
--- /dev/null
+++ b/Utilities/Sphinx/create_identifiers.py
@@ -0,0 +1,46 @@
+#!/usr/bin/env python
+
+import sys, os
+
+if len(sys.argv) != 2:
+  sys.exit(-1)
+name = sys.argv[1] + "/CMake.qhp"
+
+f = open(name)
+
+if not f:
+  sys.exit(-1)
+
+lines = f.read().splitlines()
+
+if not lines:
+  sys.exit(-1)
+
+newlines = []
+
+for line in lines:
+
+  mapping = (("command", "command"),
+             ("variable", "variable"),
+             ("target property", "prop_tgt"),
+             ("test property", "prop_test"),
+             ("source file property", "prop_sf"),
+             ("global property", "prop_gbl"),
+             ("module", "module"),
+             ("directory property", "prop_dir"),
+             ("cache property", "prop_cache"),
+             ("policy", "policy"),
+             ("installed file property", "prop_inst"))
+
+  for domain_object_string, domain_object_type in mapping:
+    if "<keyword name=\"" + domain_object_string + "\"" in line:
+      if not "id=\"" in line:
+        prefix = "<keyword name=\"" + domain_object_string + "\" "
+        part1, part2 = line.split(prefix)
+        head, tail = part2.split("#" + domain_object_type + ":")
+        domain_object, rest = tail.split("\"")
+        line = part1 + prefix + "id=\"" + domain_object_type + "/" + domain_object + "\" " + part2
+  newlines.append(line + "\n")
+
+f = open(name, "w")
+f.writelines(newlines)
diff --git a/Utilities/Sphinx/templates/layout.html b/Utilities/Sphinx/templates/layout.html
index 635ace3..1c5728c 100644
--- a/Utilities/Sphinx/templates/layout.html
+++ b/Utilities/Sphinx/templates/layout.html
@@ -11,3 +11,9 @@
     <a href="{{ pathto(master_doc) }}">{{ shorttitle|e }}</a>{{ reldelim1 }}
   </li>
 {% endblock %}
+
+{# Put some context in the html title element. Workaround for #}
+{# https://bitbucket.org/birkenfeld/sphinx/issue/1492/qthelp-generate-html-title-element-should #}
+{% block htmltitle %}
+  <title>{{ title|striptags|e }} {{ "&mdash;"|safe }} {{ docstitle|e }}</title>
+{% endblock %}
diff --git a/Utilities/cmThirdParty.h.in b/Utilities/cmThirdParty.h.in
index c824085..b0b5779 100644
--- a/Utilities/cmThirdParty.h.in
+++ b/Utilities/cmThirdParty.h.in
@@ -18,6 +18,7 @@
 #cmakedefine CMAKE_USE_SYSTEM_ZLIB
 #cmakedefine CMAKE_USE_SYSTEM_BZIP2
 #cmakedefine CMAKE_USE_SYSTEM_LIBARCHIVE
+#cmakedefine CMAKE_USE_SYSTEM_LIBLZMA
 #cmakedefine CTEST_USE_XMLRPC
 
 #endif
diff --git a/Utilities/cm_lzma.h b/Utilities/cm_lzma.h
new file mode 100644
index 0000000..c11c916
--- /dev/null
+++ b/Utilities/cm_lzma.h
@@ -0,0 +1,23 @@
+/*============================================================================
+  CMake - Cross Platform Makefile Generator
+  Copyright 2014 Kitware, Inc., Insight Software Consortium
+
+  Distributed under the OSI-approved BSD License (the "License");
+  see accompanying file Copyright.txt for details.
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the License for more information.
+============================================================================*/
+#ifndef __cm_lzma_h
+#define __cm_lzma_h
+
+/* Use the liblzma configured for CMake.  */
+#include "cmThirdParty.h"
+#ifdef CMAKE_USE_SYSTEM_LIBLZMA
+# include <lzma.h>
+#else
+# include <cmliblzma/liblzma/api/lzma.h>
+#endif
+
+#endif
diff --git a/Utilities/cmcurl/CMake/CurlCheckCSourceCompiles.cmake b/Utilities/cmcurl/CMake/CurlCheckCSourceCompiles.cmake
index cfcf47b..2f427a2 100644
--- a/Utilities/cmcurl/CMake/CurlCheckCSourceCompiles.cmake
+++ b/Utilities/cmcurl/CMake/CurlCheckCSourceCompiles.cmake
@@ -13,7 +13,7 @@
 #  CMAKE_REQUIRED_LIBRARIES = list of libraries to link
 
 MACRO(CURL_CHECK_C_SOURCE_COMPILES SOURCE VAR)
-  IF("${VAR}" MATCHES "^${VAR}$" OR "${VAR}" MATCHES "UNKNOWN")
+  IF(NOT DEFINED ${VAR} OR ${VAR} MATCHES "UNKNOWN")
     SET(message "${VAR}")
     # If the number of arguments is greater than 2 (SOURCE VAR)
     IF(${ARGC} GREATER 2)
@@ -70,5 +70,5 @@
         "${OUTPUT}\n"
         "Source file was:\n${src}\n")
     ENDIF(${VAR})
-  ENDIF("${VAR}" MATCHES "^${VAR}$" OR "${VAR}" MATCHES "UNKNOWN")
+  ENDIF()
 ENDMACRO(CURL_CHECK_C_SOURCE_COMPILES)
diff --git a/Utilities/cmcurl/CMakeLists.txt b/Utilities/cmcurl/CMakeLists.txt
index 1b918c9..03f10a0 100644
--- a/Utilities/cmcurl/CMakeLists.txt
+++ b/Utilities/cmcurl/CMakeLists.txt
@@ -505,7 +505,7 @@
 
 # For other curl specific tests, use this macro.
 MACRO(CURL_INTERNAL_TEST CURL_TEST)
-  IF("${CURL_TEST}" MATCHES "^${CURL_TEST}$")
+  IF(NOT DEFINED ${CURL_TEST})
     SET(MACRO_CHECK_FUNCTION_DEFINITIONS
       "-D${CURL_TEST} ${CMAKE_REQUIRED_FLAGS}")
     IF(CMAKE_REQUIRED_LIBRARIES)
@@ -533,7 +533,7 @@
         "Performing Curl Test ${CURL_TEST} failed with the following output:\n"
         "${OUTPUT}\n")
     ENDIF(${CURL_TEST})
-  ENDIF("${CURL_TEST}" MATCHES "^${CURL_TEST}$")
+  ENDIF()
 ENDMACRO(CURL_INTERNAL_TEST)
 
 # Do curl specific tests
diff --git a/Utilities/cmcurl/hostip.c b/Utilities/cmcurl/hostip.c
index fd555ef..83f1564 100644
--- a/Utilities/cmcurl/hostip.c
+++ b/Utilities/cmcurl/hostip.c
@@ -609,7 +609,7 @@
   h = &buf->hostentry;
   h->h_addr_list = &buf->h_addr_list[0];
   addrentry = &buf->addrentry;
-#ifdef _CRAYC
+#ifdef _CRAY
   /* On UNICOS, s_addr is a bit field and for some reason assigning to it
    * doesn't work.  There must be a better fix than this ugly hack.
    */
diff --git a/Utilities/cmlibarchive/CMakeLists.txt b/Utilities/cmlibarchive/CMakeLists.txt
index 9b1533d..f1459d4 100644
--- a/Utilities/cmlibarchive/CMakeLists.txt
+++ b/Utilities/cmlibarchive/CMakeLists.txt
@@ -275,7 +275,6 @@
 ENDIF(BZIP2_FOUND)
 MARK_AS_ADVANCED(CLEAR BZIP2_INCLUDE_DIR)
 MARK_AS_ADVANCED(CLEAR BZIP2_LIBRARIES)
-IF(0) # CMake does not need LZMA or LZO2 support in libarchive
 #
 # Find LZMA
 #
@@ -291,15 +290,19 @@
   SET(HAVE_LZMA_H 1)
   INCLUDE_DIRECTORIES(${LZMA_INCLUDE_DIR})
   LIST(APPEND ADDITIONAL_LIBS ${LZMA_LIBRARIES})
-  # Test if a macro is needed for the library.
-  TRY_MACRO_FOR_LIBRARY(
-    "${LZMA_INCLUDE_DIR}" "${LZMA_LIBRARIES}"
-    COMPILES
-    "#include <lzma.h>\nint main() {return (int)lzma_version_number(); }"
-    "WITHOUT_LZMA_API_STATIC;LZMA_API_STATIC")
-  IF(NOT WITHOUT_LZMA_API_STATIC AND LZMA_API_STATIC)
+  IF(CMAKE_USE_SYSTEM_LIBLZMA)
+    # Test if a macro is needed for the library.
+    TRY_MACRO_FOR_LIBRARY(
+      "${LZMA_INCLUDE_DIR}" "${LZMA_LIBRARIES}"
+      COMPILES
+      "#include <lzma.h>\nint main() {return (int)lzma_version_number(); }"
+      "WITHOUT_LZMA_API_STATIC;LZMA_API_STATIC")
+    IF(NOT WITHOUT_LZMA_API_STATIC AND LZMA_API_STATIC)
+      ADD_DEFINITIONS(-DLZMA_API_STATIC)
+    ENDIF(NOT WITHOUT_LZMA_API_STATIC AND LZMA_API_STATIC)
+  ELSE()
     ADD_DEFINITIONS(-DLZMA_API_STATIC)
-  ENDIF(NOT WITHOUT_LZMA_API_STATIC AND LZMA_API_STATIC)
+  ENDIF()
 ELSEIF(LZMADEC_FOUND)
   SET(HAVE_LIBLZMADEC 1)
   SET(HAVE_LZMADEC_H 1)
@@ -308,6 +311,7 @@
 ELSE(LZMA_FOUND)
 # LZMA not found and will not be used.
 ENDIF(LZMA_FOUND)
+IF(0) # CMake does not need LZO2 support in libarchive
 #
 # Find LZO2
 #
@@ -836,14 +840,14 @@
 # Check functions
 #
 CMAKE_PUSH_CHECK_STATE()	# Save the state of the variables
-IF ("CMAKE_C_COMPILER_ID" MATCHES "^GNU$")
+IF (CMAKE_C_COMPILER_ID STREQUAL "GNU")
   #
   # During checking functions, we should use -fno-builtin to avoid the
   # failure of function detection which failure is an error "conflicting
   # types for built-in function" caused by using -Werror option.
   #
   SET(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -fno-builtin")
-ENDIF ("CMAKE_C_COMPILER_ID" MATCHES "^GNU$")
+ENDIF ()
 CHECK_SYMBOL_EXISTS(_CrtSetReportMode "crtdbg.h" HAVE__CrtSetReportMode)
 CHECK_FUNCTION_EXISTS_GLIBC(chflags HAVE_CHFLAGS)
 CHECK_FUNCTION_EXISTS_GLIBC(chown HAVE_CHOWN)
diff --git a/Utilities/cmlibarchive/libarchive/archive_read_support_filter_xz.c b/Utilities/cmlibarchive/libarchive/archive_read_support_filter_xz.c
index 7bda263..a3ad67a 100644
--- a/Utilities/cmlibarchive/libarchive/archive_read_support_filter_xz.c
+++ b/Utilities/cmlibarchive/libarchive/archive_read_support_filter_xz.c
@@ -42,7 +42,7 @@
 #include <unistd.h>
 #endif
 #if HAVE_LZMA_H
-#include <lzma.h>
+#include <cm_lzma.h>
 #elif HAVE_LZMADEC_H
 #include <lzmadec.h>
 #endif
diff --git a/Utilities/cmlibarchive/libarchive/archive_read_support_format_7zip.c b/Utilities/cmlibarchive/libarchive/archive_read_support_format_7zip.c
index 8cd241b..47e0752 100644
--- a/Utilities/cmlibarchive/libarchive/archive_read_support_format_7zip.c
+++ b/Utilities/cmlibarchive/libarchive/archive_read_support_format_7zip.c
@@ -36,7 +36,7 @@
 #include <cm_bzlib.h>
 #endif
 #ifdef HAVE_LZMA_H
-#include <lzma.h>
+#include <cm_lzma.h>
 #endif
 #ifdef HAVE_ZLIB_H
 #include <cm_zlib.h>
diff --git a/Utilities/cmlibarchive/libarchive/archive_read_support_format_xar.c b/Utilities/cmlibarchive/libarchive/archive_read_support_format_xar.c
index af89ded..68485d1 100644
--- a/Utilities/cmlibarchive/libarchive/archive_read_support_format_xar.c
+++ b/Utilities/cmlibarchive/libarchive/archive_read_support_format_xar.c
@@ -42,7 +42,7 @@
 #include <cm_bzlib.h>
 #endif
 #if HAVE_LZMA_H
-#include <lzma.h>
+#include <cm_lzma.h>
 #elif HAVE_LZMADEC_H
 #include <lzmadec.h>
 #endif
diff --git a/Utilities/cmlibarchive/libarchive/archive_util.c b/Utilities/cmlibarchive/libarchive/archive_util.c
index b53beca..96b88d8 100644
--- a/Utilities/cmlibarchive/libarchive/archive_util.c
+++ b/Utilities/cmlibarchive/libarchive/archive_util.c
@@ -49,7 +49,7 @@
 #include <cm_zlib.h>
 #endif
 #ifdef HAVE_LZMA_H
-#include <lzma.h>
+#include <cm_lzma.h>
 #endif
 #ifdef HAVE_BZLIB_H
 #include <cm_bzlib.h>
diff --git a/Utilities/cmlibarchive/libarchive/archive_windows.h b/Utilities/cmlibarchive/libarchive/archive_windows.h
index 9a19cdf..dc2f241 100644
--- a/Utilities/cmlibarchive/libarchive/archive_windows.h
+++ b/Utilities/cmlibarchive/libarchive/archive_windows.h
@@ -76,6 +76,7 @@
 
 #if defined(_MSC_VER)
 #pragma warning(push,1)
+#pragma warning(disable:4142)   /* benign redefinition of type */
 #pragma warning(disable:4761)   /* integral size mismatch in argument; conversion supplied */
 #endif
 #if defined(__BORLANDC__)
diff --git a/Utilities/cmlibarchive/libarchive/archive_write_add_filter_lzop.c b/Utilities/cmlibarchive/libarchive/archive_write_add_filter_lzop.c
index 088ecea..c666551 100644
--- a/Utilities/cmlibarchive/libarchive/archive_write_add_filter_lzop.c
+++ b/Utilities/cmlibarchive/libarchive/archive_write_add_filter_lzop.c
@@ -85,7 +85,7 @@
 #if defined(HAVE_LZO_LZOCONF_H) && defined(HAVE_LZO_LZO1X_H)
 /* Maximum block size. */
 #define BLOCK_SIZE			(256 * 1024)
-/* Block infomation is composed of uncompressed size(4 bytes),
+/* Block information is composed of uncompressed size(4 bytes),
  * compressed size(4 bytes) and the checksum of uncompressed data(4 bytes)
  * in this lzop writer. */
 #define BLOCK_INfO_SIZE			12
diff --git a/Utilities/cmlibarchive/libarchive/archive_write_add_filter_xz.c b/Utilities/cmlibarchive/libarchive/archive_write_add_filter_xz.c
index fa73311..a566732 100644
--- a/Utilities/cmlibarchive/libarchive/archive_write_add_filter_xz.c
+++ b/Utilities/cmlibarchive/libarchive/archive_write_add_filter_xz.c
@@ -39,7 +39,7 @@
 #endif
 #include <time.h>
 #ifdef HAVE_LZMA_H
-#include <lzma.h>
+#include <cm_lzma.h>
 #endif
 
 #include "archive.h"
diff --git a/Utilities/cmlibarchive/libarchive/archive_write_set_format_7zip.c b/Utilities/cmlibarchive/libarchive/archive_write_set_format_7zip.c
index 4f1bc26..5158854 100644
--- a/Utilities/cmlibarchive/libarchive/archive_write_set_format_7zip.c
+++ b/Utilities/cmlibarchive/libarchive/archive_write_set_format_7zip.c
@@ -34,7 +34,7 @@
 #include <cm_bzlib.h>
 #endif
 #if HAVE_LZMA_H
-#include <lzma.h>
+#include <cm_lzma.h>
 #endif
 #ifdef HAVE_ZLIB_H
 #include <cm_zlib.h>
diff --git a/Utilities/cmlibarchive/libarchive/archive_write_set_format_mtree.c b/Utilities/cmlibarchive/libarchive/archive_write_set_format_mtree.c
index 4d343ea..b0c8018 100644
--- a/Utilities/cmlibarchive/libarchive/archive_write_set_format_mtree.c
+++ b/Utilities/cmlibarchive/libarchive/archive_write_set_format_mtree.c
@@ -1115,7 +1115,7 @@
 	do {
 		if (mtree->output_global_set) {
 			/*
-			 * Collect attribute infomation to know which value
+			 * Collect attribute information to know which value
 			 * is frequently used among the children.
 			 */
 			attr_counter_set_reset(mtree);
diff --git a/Utilities/cmlibarchive/libarchive/archive_write_set_format_xar.c b/Utilities/cmlibarchive/libarchive/archive_write_set_format_xar.c
index a4ce7ee..4cd2b9d 100644
--- a/Utilities/cmlibarchive/libarchive/archive_write_set_format_xar.c
+++ b/Utilities/cmlibarchive/libarchive/archive_write_set_format_xar.c
@@ -40,7 +40,7 @@
 #include <cm_bzlib.h>
 #endif
 #if HAVE_LZMA_H
-#include <lzma.h>
+#include <cm_lzma.h>
 #endif
 #ifdef HAVE_ZLIB_H
 #include <cm_zlib.h>
diff --git a/Utilities/cmliblzma/.gitattributes b/Utilities/cmliblzma/.gitattributes
new file mode 100644
index 0000000..562b12e
--- /dev/null
+++ b/Utilities/cmliblzma/.gitattributes
@@ -0,0 +1 @@
+* -whitespace
diff --git a/Utilities/cmliblzma/CMakeLists.txt b/Utilities/cmliblzma/CMakeLists.txt
new file mode 100644
index 0000000..23549c5
--- /dev/null
+++ b/Utilities/cmliblzma/CMakeLists.txt
@@ -0,0 +1,215 @@
+PROJECT(CMLIBLZMA C)
+
+include(CheckCSourceCompiles)
+include(CheckIncludeFile)
+include(CheckSymbolExists)
+include(CheckTypeSize)
+include(TestBigEndian)
+
+CHECK_C_SOURCE_COMPILES(
+  "int test (void *restrict x);\nint main (void) {return 0;}"
+  HAVE_RESTRICT)
+
+CHECK_C_SOURCE_COMPILES(
+"typedef struct abc *d;\nint test (d __restrict x);\nint main (void) {return 0;}"
+  HAVE___RESTRICT)
+
+CHECK_C_SOURCE_COMPILES(
+  "inline int test (void) {return 0;}\nint main (void) {return test();}"
+  HAVE_INLINE)
+
+CHECK_C_SOURCE_COMPILES (
+  "__inline int test (void) {return 0;}\nint main (void) {return test();}"
+  HAVE___INLINE)
+
+CHECK_INCLUDE_FILE(byteswap.h HAVE_BYTESWAP_H)
+CHECK_INCLUDE_FILE(inttypes.h HAVE_INTTYPES_H)
+CHECK_INCLUDE_FILE(limits.h HAVE_LIMITS_H)
+CHECK_INCLUDE_FILE(memory.h HAVE_MEMORY_H)
+CHECK_INCLUDE_FILE(strings.h HAVE_STRINGS_H)
+CHECK_INCLUDE_FILE(string.h HAVE_STRING_H)
+CHECK_INCLUDE_FILE(sys/sysctl.h HAVE_SYS_SYSCTL_H)
+
+CHECK_INCLUDE_FILE(stdbool.h HAVE_STDBOOL_H)
+if(NOT HAVE_STDBOOL_H)
+  CHECK_TYPE_SIZE(_Bool _BOOL)
+endif()
+
+CHECK_C_SOURCE_COMPILES (
+  "#include<byteswap.h>\nint main(void){bswap_16(0);return 0;}"
+  HAVE_BSWAP_16)
+CHECK_C_SOURCE_COMPILES (
+  "#include<byteswap.h>\nint main(void){bswap_32(0);return 0;}"
+  HAVE_BSWAP_32)
+CHECK_C_SOURCE_COMPILES (
+  "#include<byteswap.h>\nint main(void){bswap_64(0);return 0;}"
+  HAVE_BSWAP_64)
+
+TEST_BIG_ENDIAN(WORDS_BIGENDIAN)
+
+set(HAVE_CHECK_CRC64 1)
+set(HAVE_CHECK_SHA256 1)
+
+set(HAVE_DECODER_ARM 1)
+set(HAVE_DECODER_ARMTHUMB 1)
+set(HAVE_DECODER_DELTA 1)
+set(HAVE_DECODER_IA64 1)
+set(HAVE_DECODER_LZMA1 1)
+set(HAVE_DECODER_LZMA2 1)
+set(HAVE_DECODER_POWERPC 1)
+set(HAVE_DECODER_SPARC 1)
+set(HAVE_DECODER_X86 1)
+
+set(HAVE_ENCODER_ARM 1)
+set(HAVE_ENCODER_ARMTHUMB 1)
+set(HAVE_ENCODER_DELTA 1)
+set(HAVE_ENCODER_IA64 1)
+set(HAVE_ENCODER_LZMA1 1)
+set(HAVE_ENCODER_LZMA2 1)
+set(HAVE_ENCODER_POWERPC 1)
+set(HAVE_ENCODER_SPARC 1)
+set(HAVE_ENCODER_X86 1)
+
+set(HAVE_MF_BT2 1)
+set(HAVE_MF_BT3 1)
+set(HAVE_MF_BT4 1)
+set(HAVE_MF_HC3 1)
+set(HAVE_MF_HC4 1)
+
+CHECK_TYPE_SIZE(int16_t INT16_T)
+CHECK_TYPE_SIZE(int32_t INT32_T)
+CHECK_TYPE_SIZE(int64_t INT64_T)
+CHECK_TYPE_SIZE(intmax_t INTMAX_T)
+CHECK_TYPE_SIZE(uint8_t UINT8_T)
+CHECK_TYPE_SIZE(uint16_t UINT16_T)
+CHECK_TYPE_SIZE(uint32_t UINT32_T)
+CHECK_TYPE_SIZE(uint64_t UINT64_T)
+CHECK_TYPE_SIZE(uintmax_t UINTMAX_T)
+
+CHECK_TYPE_SIZE("short" SIZE_OF_SHORT)
+CHECK_TYPE_SIZE("int" SIZE_OF_INT)
+CHECK_TYPE_SIZE("long" SIZE_OF_LONG)
+CHECK_TYPE_SIZE("long long" SIZE_OF_LONG_LONG)
+
+CHECK_TYPE_SIZE("unsigned short" SIZE_OF_UNSIGNED_SHORT)
+CHECK_TYPE_SIZE("unsigned" SIZE_OF_UNSIGNED)
+CHECK_TYPE_SIZE("unsigned long" SIZE_OF_UNSIGNED_LONG)
+CHECK_TYPE_SIZE("unsigned long long" SIZE_OF_UNSIGNED_LONG_LONG)
+
+CHECK_TYPE_SIZE("__int64" __INT64)
+CHECK_TYPE_SIZE("unsigned __int64" UNSIGNED___INT64)
+
+CHECK_TYPE_SIZE(uintptr_t UINTPTR_T)
+IF(NOT HAVE_UINTPTR_T)
+  IF("${CMAKE_SIZEOF_VOID_P}" EQUAL 8)
+    SET(uintptr_t "uint64_t")
+  ELSE()
+    SET(uintptr_t "uint32_t")
+  ENDIF()
+ENDIF()
+
+
+SET(LZMA_SRCS
+  common/sysdefs.h
+  common/tuklib_integer.h
+  liblzma/check/check.c
+  liblzma/check/crc32_fast.c
+  liblzma/check/crc32_table.c
+  liblzma/check/crc64_fast.c
+  liblzma/check/crc64_table.c
+  liblzma/check/sha256.c
+  liblzma/common/alone_decoder.c
+  liblzma/common/alone_encoder.c
+  liblzma/common/auto_decoder.c
+  liblzma/common/block_buffer_decoder.c
+  liblzma/common/block_buffer_encoder.c
+  liblzma/common/block_decoder.c
+  liblzma/common/block_encoder.c
+  liblzma/common/block_header_decoder.c
+  liblzma/common/block_header_encoder.c
+  liblzma/common/block_util.c
+  liblzma/common/common.c
+  liblzma/common/easy_buffer_encoder.c
+  liblzma/common/easy_decoder_memusage.c
+  liblzma/common/easy_encoder.c
+  liblzma/common/easy_encoder_memusage.c
+  liblzma/common/easy_preset.c
+  liblzma/common/filter_buffer_decoder.c
+  liblzma/common/filter_buffer_encoder.c
+  liblzma/common/filter_common.c
+  liblzma/common/filter_decoder.c
+  liblzma/common/filter_encoder.c
+  liblzma/common/filter_flags_decoder.c
+  liblzma/common/filter_flags_encoder.c
+  liblzma/common/index.c
+  liblzma/common/index_decoder.c
+  liblzma/common/index_encoder.c
+  liblzma/common/index_hash.c
+  liblzma/common/stream_buffer_decoder.c
+  liblzma/common/stream_buffer_encoder.c
+  liblzma/common/stream_decoder.c
+  liblzma/common/stream_encoder.c
+  liblzma/common/stream_flags_common.c
+  liblzma/common/stream_flags_decoder.c
+  liblzma/common/stream_flags_encoder.c
+  liblzma/common/vli_decoder.c
+  liblzma/common/vli_encoder.c
+  liblzma/common/vli_size.c
+  liblzma/delta/delta_common.c
+  liblzma/delta/delta_decoder.c
+  liblzma/delta/delta_encoder.c
+  liblzma/lz/lz_decoder.c
+  liblzma/lz/lz_encoder.c
+  liblzma/lz/lz_encoder_mf.c
+  liblzma/lzma/fastpos_table.c
+  liblzma/lzma/lzma2_decoder.c
+  liblzma/lzma/lzma2_encoder.c
+  liblzma/lzma/lzma_decoder.c
+  liblzma/lzma/lzma_encoder.c
+  liblzma/lzma/lzma_encoder_optimum_fast.c
+  liblzma/lzma/lzma_encoder_optimum_normal.c
+  liblzma/lzma/lzma_encoder_presets.c
+  liblzma/rangecoder/price_table.c
+  liblzma/simple/arm.c
+  liblzma/simple/armthumb.c
+  liblzma/simple/ia64.c
+  liblzma/simple/powerpc.c
+  liblzma/simple/simple_coder.c
+  liblzma/simple/simple_decoder.c
+  liblzma/simple/simple_encoder.c
+  liblzma/simple/sparc.c
+  liblzma/simple/x86.c
+  )
+
+IF(WIN32 AND BUILD_SHARED_LIBS)
+  SET(LZMA_SRCS ${LZMA_SRCS} liblzma/liblzma_w32res.rc)
+ENDIF()
+
+CONFIGURE_FILE(config.h.in config.h @ONLY)
+
+INCLUDE_DIRECTORIES(
+  "${CMLIBLZMA_SOURCE_DIR}/common"
+  "${CMLIBLZMA_SOURCE_DIR}/liblzma/api"
+  "${CMLIBLZMA_SOURCE_DIR}/liblzma/check"
+  "${CMLIBLZMA_SOURCE_DIR}/liblzma/common"
+  "${CMLIBLZMA_SOURCE_DIR}/liblzma/delta"
+  "${CMLIBLZMA_SOURCE_DIR}/liblzma/lz"
+  "${CMLIBLZMA_SOURCE_DIR}/liblzma/lzma"
+  "${CMLIBLZMA_SOURCE_DIR}/liblzma/rangecoder"
+  "${CMLIBLZMA_SOURCE_DIR}/liblzma/simple"
+  "${CMLIBLZMA_BINARY_DIR}"
+  )
+
+# Disable warnings to avoid changing 3rd party code.
+IF("${CMAKE_C_COMPILER_ID}" MATCHES
+    "^(GNU|Clang|AppleClang|XL|VisualAge|SunPro|MIPSpro|HP|Intel)$")
+  SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -w")
+ELSEIF("${CMAKE_C_COMPILER_ID}" MATCHES "^(PathScale)$")
+  SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -woffall")
+ELSEIF(BORLAND)
+  SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -w-")
+ENDIF()
+
+ADD_LIBRARY(cmliblzma ${LZMA_SRCS})
+
+INSTALL(FILES COPYING DESTINATION ${CMAKE_DOC_DIR}/cmliblzma)
diff --git a/Utilities/cmliblzma/COPYING b/Utilities/cmliblzma/COPYING
new file mode 100644
index 0000000..43c90d0
--- /dev/null
+++ b/Utilities/cmliblzma/COPYING
@@ -0,0 +1,65 @@
+
+XZ Utils Licensing
+==================
+
+    Different licenses apply to different files in this package. Here
+    is a rough summary of which licenses apply to which parts of this
+    package (but check the individual files to be sure!):
+
+      - liblzma is in the public domain.
+
+      - xz, xzdec, and lzmadec command line tools are in the public
+        domain unless GNU getopt_long had to be compiled and linked
+        in from the lib directory. The getopt_long code is under
+        GNU LGPLv2.1+.
+
+      - The scripts to grep, diff, and view compressed files have been
+        adapted from gzip. These scripts and their documentation are
+        under GNU GPLv2+.
+
+      - All the documentation in the doc directory and most of the
+        XZ Utils specific documentation files in other directories
+        are in the public domain.
+
+      - Translated messages are in the public domain.
+
+      - The build system contains public domain files, and files that
+        are under GNU GPLv2+ or GNU GPLv3+. None of these files end up
+        in the binaries being built.
+
+      - Test files and test code in the tests directory, and debugging
+        utilities in the debug directory are in the public domain.
+
+      - The extra directory may contain public domain files, and files
+        that are under various free software licenses.
+
+    You can do whatever you want with the files that have been put into
+    the public domain. If you find public domain legally problematic,
+    take the previous sentence as a license grant. If you still find
+    the lack of copyright legally problematic, you have too many
+    lawyers.
+
+    As usual, this software is provided "as is", without any warranty.
+
+    If you copy significant amounts of public domain code from XZ Utils
+    into your project, acknowledging this somewhere in your software is
+    polite (especially if it is proprietary, non-free software), but
+    naturally it is not legally required. Here is an example of a good
+    notice to put into "about box" or into documentation:
+
+        This software includes code from XZ Utils <http://tukaani.org/xz/>.
+
+    The following license texts are included in the following files:
+      - COPYING.LGPLv2.1: GNU Lesser General Public License version 2.1
+      - COPYING.GPLv2: GNU General Public License version 2
+      - COPYING.GPLv3: GNU General Public License version 3
+
+    Note that the toolchain (compiler, linker etc.) may add some code
+    pieces that are copyrighted. Thus, it is possible that e.g. liblzma
+    binary wouldn't actually be in the public domain in its entirety
+    even though it contains no copyrighted code from the XZ Utils source
+    package.
+
+    If you have questions, don't hesitate to ask the author(s) for more
+    information.
+
diff --git a/Utilities/cmliblzma/README-CMake.txt b/Utilities/cmliblzma/README-CMake.txt
new file mode 100644
index 0000000..b512997
--- /dev/null
+++ b/Utilities/cmliblzma/README-CMake.txt
@@ -0,0 +1,66 @@
+The Utilities/cmliblzma directory contains a reduced distribution
+of the liblzma source tree with only the library source code and
+CMake build system.  It is not a submodule; the actual content is part
+of our source tree and changes can be made and committed directly.
+
+We update from upstream using Git's "subtree" merge strategy.  A
+special branch contains commits of upstream liblzma snapshots and
+nothing else.  No Git ref points explicitly to the head of this
+branch, but it is merged into our history.
+
+Update liblzma from upstream as follows.  Create a local branch to
+explicitly reference the upstream snapshot branch head:
+
+ git branch liblzma-upstream c289e634
+
+Use a temporary directory to checkout the branch:
+
+ mkdir liblzma-tmp
+ cd liblzma-tmp
+ git init
+ git pull .. liblzma-upstream
+ rm -rf *
+
+Now place the (reduced) liblzma content in this directory.  See
+instructions shown by
+
+ git log c289e634
+
+for help extracting the content from the upstream svn repo.  Then run
+the following commands to commit the new version.  Substitute the
+appropriate date and version number:
+
+ git add --all
+
+ GIT_AUTHOR_NAME='liblzma upstream' \
+ GIT_AUTHOR_EMAIL='xz-devel@tukaani.org' \
+ GIT_AUTHOR_DATE='Sun Jun 30 19:55:49 2013 +0300' \
+ git commit -m 'liblzma 5.0.5-gb69900ed (reduced)' &&
+ git commit --amend
+
+Edit the commit message to describe the procedure used to obtain the
+content.  Then push the changes back up to the main local repository:
+
+ git push .. HEAD:liblzma-upstream
+ cd ..
+ rm -rf liblzma-tmp
+
+Create a topic in the main repository on which to perform the update:
+
+ git checkout -b update-liblzma master
+
+Merge the liblzma-upstream branch as a subtree:
+
+ git merge -s recursive -X subtree=Utilities/cmliblzma \
+           liblzma-upstream
+
+If there are conflicts, resolve them and commit.  Build and test the
+tree.  Commit any additional changes needed to succeed.
+
+Finally, run
+
+ git rev-parse --short=8 liblzma-upstream
+
+to get the commit from which the liblzma-upstream branch must be started
+on the next update.  Edit the "git branch liblzma-upstream" line above to
+record it, and commit this file.
diff --git a/Utilities/cmliblzma/common/common_w32res.rc b/Utilities/cmliblzma/common/common_w32res.rc
new file mode 100644
index 0000000..fdb88d1
--- /dev/null
+++ b/Utilities/cmliblzma/common/common_w32res.rc
@@ -0,0 +1,50 @@
+/*
+ * Author: Lasse Collin
+ *
+ * This file has been put into the public domain.
+ * You can do whatever you want with this file.
+ */
+
+#include <winresrc.h>
+#include "config.h"
+#define LZMA_H_INTERNAL
+#define LZMA_H_INTERNAL_RC
+#include "lzma/version.h"
+
+#ifndef MY_BUILD
+# define MY_BUILD 0
+#endif
+#define MY_VERSION LZMA_VERSION_MAJOR,LZMA_VERSION_MINOR,LZMA_VERSION_PATCH,MY_BUILD
+
+#define MY_FILENAME    MY_NAME MY_SUFFIX
+#define MY_COMPANY     "The Tukaani Project <http://tukaani.org/>"
+#define MY_PRODUCT     PACKAGE_NAME " <" PACKAGE_URL ">"
+
+LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
+VS_VERSION_INFO VERSIONINFO
+  FILEVERSION MY_VERSION
+  PRODUCTVERSION MY_VERSION
+  FILEFLAGSMASK VS_FFI_FILEFLAGSMASK
+  FILEFLAGS 0
+  FILEOS VOS_NT_WINDOWS32
+  FILETYPE MY_TYPE
+  FILESUBTYPE 0x0L
+BEGIN
+    BLOCK "StringFileInfo"
+    BEGIN
+        BLOCK "040904b0"
+        BEGIN
+            VALUE "CompanyName", MY_COMPANY
+            VALUE "FileDescription", MY_DESC
+            VALUE "FileVersion", LZMA_VERSION_STRING
+            VALUE "InternalName", MY_NAME
+            VALUE "OriginalFilename", MY_FILENAME
+            VALUE "ProductName", MY_PRODUCT
+            VALUE "ProductVersion", LZMA_VERSION_STRING
+        END
+    END
+    BLOCK "VarFileInfo"
+    BEGIN
+        VALUE "Translation", 0x409, 1200
+    END
+END
diff --git a/Utilities/cmliblzma/common/sysdefs.h b/Utilities/cmliblzma/common/sysdefs.h
new file mode 100644
index 0000000..c84f01c
--- /dev/null
+++ b/Utilities/cmliblzma/common/sysdefs.h
@@ -0,0 +1,202 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       sysdefs.h
+/// \brief      Common includes, definitions, system-specific things etc.
+///
+/// This file is used also by the lzma command line tool, that's why this
+/// file is separate from common.h.
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#ifndef LZMA_SYSDEFS_H
+#define LZMA_SYSDEFS_H
+
+#if defined(_MSC_VER)
+# pragma warning(push,1)
+# pragma warning(disable: 4142) /* benign redefinition of type */
+# pragma warning(disable: 4761) /* integral size mismatch in argument */
+#endif
+
+//////////////
+// Includes //
+//////////////
+
+#include "config.h"
+
+// Get standard-compliant stdio functions under MinGW and MinGW-w64.
+#ifdef __MINGW32__
+#	define __USE_MINGW_ANSI_STDIO 1
+#endif
+
+// size_t and NULL
+#include <stddef.h>
+
+#ifdef HAVE_INTTYPES_H
+#	include <inttypes.h>
+#endif
+
+// C99 says that inttypes.h always includes stdint.h, but some systems
+// don't do that, and require including stdint.h separately.
+#ifdef HAVE_STDINT_H
+#	include <stdint.h>
+#endif
+
+// Some pre-C99 systems have SIZE_MAX in limits.h instead of stdint.h. The
+// limits are also used to figure out some macros missing from pre-C99 systems.
+#ifdef HAVE_LIMITS_H
+#	include <limits.h>
+#endif
+
+
+#if defined(_MSC_VER) && (_MSC_VER < 1310)
+#  define UINT64_C(n) n ## ui64
+#endif
+
+
+// Be more compatible with systems that have non-conforming inttypes.h.
+// We assume that int is 32-bit and that long is either 32-bit or 64-bit.
+// Full Autoconf test could be more correct, but this should work well enough.
+// Note that this duplicates some code from lzma.h, but this is better since
+// we can work without inttypes.h thanks to Autoconf tests.
+#ifndef UINT32_C
+#	if UINT_MAX != 4294967295U
+#		error UINT32_C is not defined and unsigned int is not 32-bit.
+#	endif
+#	define UINT32_C(n) n ## U
+#endif
+#ifndef UINT32_MAX
+#	define UINT32_MAX UINT32_C(4294967295)
+#endif
+#ifndef PRIu32
+#	define PRIu32 "u"
+#endif
+#ifndef PRIx32
+#	define PRIx32 "x"
+#endif
+#ifndef PRIX32
+#	define PRIX32 "X"
+#endif
+
+#if ULONG_MAX == 4294967295UL
+#	ifndef UINT64_C
+#		define UINT64_C(n) n ## ULL
+#	endif
+#	ifndef PRIu64
+#		define PRIu64 "llu"
+#	endif
+#	ifndef PRIx64
+#		define PRIx64 "llx"
+#	endif
+#	ifndef PRIX64
+#		define PRIX64 "llX"
+#	endif
+#else
+#	ifndef UINT64_C
+#		define UINT64_C(n) n ## UL
+#	endif
+#	ifndef PRIu64
+#		define PRIu64 "lu"
+#	endif
+#	ifndef PRIx64
+#		define PRIx64 "lx"
+#	endif
+#	ifndef PRIX64
+#		define PRIX64 "lX"
+#	endif
+#endif
+#ifndef UINT64_MAX
+#	define UINT64_MAX UINT64_C(18446744073709551615)
+#endif
+
+// Incorrect(?) SIZE_MAX:
+//   - Interix headers typedef size_t to unsigned long,
+//     but a few lines later define SIZE_MAX to INT32_MAX.
+//   - SCO OpenServer (x86) headers typedef size_t to unsigned int
+//     but define SIZE_MAX to INT32_MAX.
+#if defined(__INTERIX) || defined(_SCO_DS)
+#	undef SIZE_MAX
+#endif
+
+// The code currently assumes that size_t is either 32-bit or 64-bit.
+#ifndef SIZE_MAX
+#	if SIZEOF_SIZE_T == 4
+#		define SIZE_MAX UINT32_MAX
+#	elif SIZEOF_SIZE_T == 8
+#		define SIZE_MAX UINT64_MAX
+#	else
+#		error size_t is not 32-bit or 64-bit
+#	endif
+#endif
+#if SIZE_MAX != UINT32_MAX && SIZE_MAX != UINT64_MAX
+#	error size_t is not 32-bit or 64-bit
+#endif
+
+#include <stdlib.h>
+#include <assert.h>
+
+// Pre-C99 systems lack stdbool.h. All the code in LZMA Utils must be written
+// so that it works with fake bool type, for example:
+//
+//    bool foo = (flags & 0x100) != 0;
+//    bool bar = !!(flags & 0x100);
+//
+// This works with the real C99 bool but breaks with fake bool:
+//
+//    bool baz = (flags & 0x100);
+//
+#ifdef HAVE_STDBOOL_H
+#	include <stdbool.h>
+#else
+#	if ! HAVE__BOOL
+typedef unsigned char _Bool;
+#	endif
+#	define bool _Bool
+#	define false 0
+#	define true 1
+#	define __bool_true_false_are_defined 1
+#endif
+
+// string.h should be enough but let's include strings.h and memory.h too if
+// they exists, since that shouldn't do any harm, but may improve portability.
+#ifdef HAVE_STRING_H
+#	include <string.h>
+#endif
+
+#ifdef HAVE_STRINGS_H
+#	include <strings.h>
+#endif
+
+#ifdef HAVE_MEMORY_H
+#	include <memory.h>
+#endif
+
+
+////////////
+// Macros //
+////////////
+
+#undef memzero
+#define memzero(s, n) memset(s, 0, n)
+
+// NOTE: Avoid using MIN() and MAX(), because even conditionally defining
+// those macros can cause some portability trouble, since on some systems
+// the system headers insist defining their own versions.
+#define my_min(x, y) ((x) < (y) ? (x) : (y))
+#define my_max(x, y) ((x) > (y) ? (x) : (y))
+
+#ifndef ARRAY_SIZE
+#	define ARRAY_SIZE(array) (sizeof(array) / sizeof((array)[0]))
+#endif
+
+#if (__GNUC__ == 4 && __GNUC_MINOR__ >= 3) || __GNUC__ > 4
+#	define lzma_attr_alloc_size(x) __attribute__((__alloc_size__(x)))
+#else
+#	define lzma_attr_alloc_size(x)
+#endif
+
+#endif
diff --git a/Utilities/cmliblzma/common/tuklib_integer.h b/Utilities/cmliblzma/common/tuklib_integer.h
new file mode 100644
index 0000000..5e8262a
--- /dev/null
+++ b/Utilities/cmliblzma/common/tuklib_integer.h
@@ -0,0 +1,514 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       tuklib_integer.h
+/// \brief      Various integer and bit operations
+///
+/// This file provides macros or functions to do some basic integer and bit
+/// operations.
+///
+/// Endianness related integer operations (XX = 16, 32, or 64; Y = b or l):
+///   - Byte swapping: bswapXX(num)
+///   - Byte order conversions to/from native: convXXYe(num)
+///   - Aligned reads: readXXYe(ptr)
+///   - Aligned writes: writeXXYe(ptr, num)
+///   - Unaligned reads (16/32-bit only): unaligned_readXXYe(ptr)
+///   - Unaligned writes (16/32-bit only): unaligned_writeXXYe(ptr, num)
+///
+/// Since they can macros, the arguments should have no side effects since
+/// they may be evaluated more than once.
+///
+/// \todo       PowerPC and possibly some other architectures support
+///             byte swapping load and store instructions. This file
+///             doesn't take advantage of those instructions.
+///
+/// Bit scan operations for non-zero 32-bit integers:
+///   - Bit scan reverse (find highest non-zero bit): bsr32(num)
+///   - Count leading zeros: clz32(num)
+///   - Count trailing zeros: ctz32(num)
+///   - Bit scan forward (simply an alias for ctz32()): bsf32(num)
+///
+/// The above bit scan operations return 0-31. If num is zero,
+/// the result is undefined.
+//
+//  Authors:    Lasse Collin
+//              Joachim Henke
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#ifndef TUKLIB_INTEGER_H
+#define TUKLIB_INTEGER_H
+
+#include "sysdefs.h"
+
+#if defined(__GNUC__) && defined(__GNUC_MINOR__)
+#   define TUKLIB_GNUC_REQ(major, minor) \
+        ((__GNUC__ == (major) && __GNUC_MINOR__ >= (minor)) \
+            || __GNUC__ > (major))
+#else
+#   define TUKLIB_GNUC_REQ(major, minor) 0
+#endif
+
+
+////////////////////////////////////////
+// Operating system specific features //
+////////////////////////////////////////
+
+#if defined(HAVE_BYTESWAP_H)
+	// glibc, uClibc, dietlibc
+#	include <byteswap.h>
+#	ifdef HAVE_BSWAP_16
+#		define bswap16(num) bswap_16(num)
+#	endif
+#	ifdef HAVE_BSWAP_32
+#		define bswap32(num) bswap_32(num)
+#	endif
+#	ifdef HAVE_BSWAP_64
+#		define bswap64(num) bswap_64(num)
+#	endif
+
+#elif defined(HAVE_SYS_ENDIAN_H)
+	// *BSDs and Darwin
+#	include <sys/endian.h>
+
+#elif defined(HAVE_SYS_BYTEORDER_H)
+	// Solaris
+#	include <sys/byteorder.h>
+#	ifdef BSWAP_16
+#		define bswap16(num) BSWAP_16(num)
+#	endif
+#	ifdef BSWAP_32
+#		define bswap32(num) BSWAP_32(num)
+#	endif
+#	ifdef BSWAP_64
+#		define bswap64(num) BSWAP_64(num)
+#	endif
+#	ifdef BE_16
+#		define conv16be(num) BE_16(num)
+#	endif
+#	ifdef BE_32
+#		define conv32be(num) BE_32(num)
+#	endif
+#	ifdef BE_64
+#		define conv64be(num) BE_64(num)
+#	endif
+#	ifdef LE_16
+#		define conv16le(num) LE_16(num)
+#	endif
+#	ifdef LE_32
+#		define conv32le(num) LE_32(num)
+#	endif
+#	ifdef LE_64
+#		define conv64le(num) LE_64(num)
+#	endif
+#endif
+
+
+///////////////////
+// Byte swapping //
+///////////////////
+
+#ifndef bswap16
+#	define bswap16(num) \
+		(((uint16_t)(num) << 8) | ((uint16_t)(num) >> 8))
+#endif
+
+#ifndef bswap32
+#	define bswap32(num) \
+		( (((uint32_t)(num) << 24)                       ) \
+		| (((uint32_t)(num) <<  8) & UINT32_C(0x00FF0000)) \
+		| (((uint32_t)(num) >>  8) & UINT32_C(0x0000FF00)) \
+		| (((uint32_t)(num) >> 24)                       ) )
+#endif
+
+#ifndef bswap64
+#	define bswap64(num) \
+		( (((uint64_t)(num) << 56)                               ) \
+		| (((uint64_t)(num) << 40) & UINT64_C(0x00FF000000000000)) \
+		| (((uint64_t)(num) << 24) & UINT64_C(0x0000FF0000000000)) \
+		| (((uint64_t)(num) <<  8) & UINT64_C(0x000000FF00000000)) \
+		| (((uint64_t)(num) >>  8) & UINT64_C(0x00000000FF000000)) \
+		| (((uint64_t)(num) >> 24) & UINT64_C(0x0000000000FF0000)) \
+		| (((uint64_t)(num) >> 40) & UINT64_C(0x000000000000FF00)) \
+		| (((uint64_t)(num) >> 56)                               ) )
+#endif
+
+// Define conversion macros using the basic byte swapping macros.
+#ifdef WORDS_BIGENDIAN
+#	ifndef conv16be
+#		define conv16be(num) ((uint16_t)(num))
+#	endif
+#	ifndef conv32be
+#		define conv32be(num) ((uint32_t)(num))
+#	endif
+#	ifndef conv64be
+#		define conv64be(num) ((uint64_t)(num))
+#	endif
+#	ifndef conv16le
+#		define conv16le(num) bswap16(num)
+#	endif
+#	ifndef conv32le
+#		define conv32le(num) bswap32(num)
+#	endif
+#	ifndef conv64le
+#		define conv64le(num) bswap64(num)
+#	endif
+#else
+#	ifndef conv16be
+#		define conv16be(num) bswap16(num)
+#	endif
+#	ifndef conv32be
+#		define conv32be(num) bswap32(num)
+#	endif
+#	ifndef conv64be
+#		define conv64be(num) bswap64(num)
+#	endif
+#	ifndef conv16le
+#		define conv16le(num) ((uint16_t)(num))
+#	endif
+#	ifndef conv32le
+#		define conv32le(num) ((uint32_t)(num))
+#	endif
+#	ifndef conv64le
+#		define conv64le(num) ((uint64_t)(num))
+#	endif
+#endif
+
+
+//////////////////////////////
+// Aligned reads and writes //
+//////////////////////////////
+
+static inline uint16_t
+read16be(const uint8_t *buf)
+{
+	uint16_t num = *(const uint16_t *)buf;
+	return conv16be(num);
+}
+
+
+static inline uint16_t
+read16le(const uint8_t *buf)
+{
+	uint16_t num = *(const uint16_t *)buf;
+	return conv16le(num);
+}
+
+
+static inline uint32_t
+read32be(const uint8_t *buf)
+{
+	uint32_t num = *(const uint32_t *)buf;
+	return conv32be(num);
+}
+
+
+static inline uint32_t
+read32le(const uint8_t *buf)
+{
+	uint32_t num = *(const uint32_t *)buf;
+	return conv32le(num);
+}
+
+
+static inline uint64_t
+read64be(const uint8_t *buf)
+{
+	uint64_t num = *(const uint64_t *)buf;
+	return conv64be(num);
+}
+
+
+static inline uint64_t
+read64le(const uint8_t *buf)
+{
+	uint64_t num = *(const uint64_t *)buf;
+	return conv64le(num);
+}
+
+
+// NOTE: Possible byte swapping must be done in a macro to allow GCC
+// to optimize byte swapping of constants when using glibc's or *BSD's
+// byte swapping macros. The actual write is done in an inline function
+// to make type checking of the buf pointer possible similarly to readXXYe()
+// functions.
+
+#define write16be(buf, num) write16ne((buf), conv16be(num))
+#define write16le(buf, num) write16ne((buf), conv16le(num))
+#define write32be(buf, num) write32ne((buf), conv32be(num))
+#define write32le(buf, num) write32ne((buf), conv32le(num))
+#define write64be(buf, num) write64ne((buf), conv64be(num))
+#define write64le(buf, num) write64ne((buf), conv64le(num))
+
+
+static inline void
+write16ne(uint8_t *buf, uint16_t num)
+{
+	*(uint16_t *)buf = num;
+	return;
+}
+
+
+static inline void
+write32ne(uint8_t *buf, uint32_t num)
+{
+	*(uint32_t *)buf = num;
+	return;
+}
+
+
+static inline void
+write64ne(uint8_t *buf, uint64_t num)
+{
+	*(uint64_t *)buf = num;
+	return;
+}
+
+
+////////////////////////////////
+// Unaligned reads and writes //
+////////////////////////////////
+
+// NOTE: TUKLIB_FAST_UNALIGNED_ACCESS indicates only support for 16-bit and
+// 32-bit unaligned integer loads and stores. It's possible that 64-bit
+// unaligned access doesn't work or is slower than byte-by-byte access.
+// Since unaligned 64-bit is probably not needed as often as 16-bit or
+// 32-bit, we simply don't support 64-bit unaligned access for now.
+#ifdef TUKLIB_FAST_UNALIGNED_ACCESS
+#	define unaligned_read16be read16be
+#	define unaligned_read16le read16le
+#	define unaligned_read32be read32be
+#	define unaligned_read32le read32le
+#	define unaligned_write16be write16be
+#	define unaligned_write16le write16le
+#	define unaligned_write32be write32be
+#	define unaligned_write32le write32le
+
+#else
+
+static inline uint16_t
+unaligned_read16be(const uint8_t *buf)
+{
+	uint16_t num = ((uint16_t)buf[0] << 8) | (uint16_t)buf[1];
+	return num;
+}
+
+
+static inline uint16_t
+unaligned_read16le(const uint8_t *buf)
+{
+	uint16_t num = ((uint16_t)buf[0]) | ((uint16_t)buf[1] << 8);
+	return num;
+}
+
+
+static inline uint32_t
+unaligned_read32be(const uint8_t *buf)
+{
+	uint32_t num = (uint32_t)buf[0] << 24;
+	num |= (uint32_t)buf[1] << 16;
+	num |= (uint32_t)buf[2] << 8;
+	num |= (uint32_t)buf[3];
+	return num;
+}
+
+
+static inline uint32_t
+unaligned_read32le(const uint8_t *buf)
+{
+	uint32_t num = (uint32_t)buf[0];
+	num |= (uint32_t)buf[1] << 8;
+	num |= (uint32_t)buf[2] << 16;
+	num |= (uint32_t)buf[3] << 24;
+	return num;
+}
+
+
+static inline void
+unaligned_write16be(uint8_t *buf, uint16_t num)
+{
+	buf[0] = num >> 8;
+	buf[1] = num;
+	return;
+}
+
+
+static inline void
+unaligned_write16le(uint8_t *buf, uint16_t num)
+{
+	buf[0] = num;
+	buf[1] = num >> 8;
+	return;
+}
+
+
+static inline void
+unaligned_write32be(uint8_t *buf, uint32_t num)
+{
+	buf[0] = num >> 24;
+	buf[1] = num >> 16;
+	buf[2] = num >> 8;
+	buf[3] = num;
+	return;
+}
+
+
+static inline void
+unaligned_write32le(uint8_t *buf, uint32_t num)
+{
+	buf[0] = num;
+	buf[1] = num >> 8;
+	buf[2] = num >> 16;
+	buf[3] = num >> 24;
+	return;
+}
+
+#endif
+
+
+static inline uint32_t
+bsr32(uint32_t n)
+{
+	// Check for ICC first, since it tends to define __GNUC__ too.
+#if defined(__INTEL_COMPILER)
+	return _bit_scan_reverse(n);
+
+#elif TUKLIB_GNUC_REQ(3, 4) && UINT_MAX == UINT32_MAX
+	// GCC >= 3.4 has __builtin_clz(), which gives good results on
+	// multiple architectures. On x86, __builtin_clz() ^ 31U becomes
+	// either plain BSR (so the XOR gets optimized away) or LZCNT and
+	// XOR (if -march indicates that SSE4a instructions are supported).
+	return __builtin_clz(n) ^ 31U;
+
+#elif defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))
+	uint32_t i;
+	__asm__("bsrl %1, %0" : "=r" (i) : "rm" (n));
+	return i;
+
+#else
+	uint32_t i = 31;
+
+	if ((n & UINT32_C(0xFFFF0000)) == 0) {
+		n <<= 16;
+		i = 15;
+	}
+
+	if ((n & UINT32_C(0xFF000000)) == 0) {
+		n <<= 8;
+		i -= 8;
+	}
+
+	if ((n & UINT32_C(0xF0000000)) == 0) {
+		n <<= 4;
+		i -= 4;
+	}
+
+	if ((n & UINT32_C(0xC0000000)) == 0) {
+		n <<= 2;
+		i -= 2;
+	}
+
+	if ((n & UINT32_C(0x80000000)) == 0)
+		--i;
+
+	return i;
+#endif
+}
+
+
+static inline uint32_t
+clz32(uint32_t n)
+{
+#if defined(__INTEL_COMPILER)
+	return _bit_scan_reverse(n) ^ 31U;
+
+#elif TUKLIB_GNUC_REQ(3, 4) && UINT_MAX == UINT32_MAX
+	return __builtin_clz(n);
+
+#elif defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))
+	uint32_t i;
+	__asm__("bsrl %1, %0\n\t"
+		"xorl $31, %0"
+		: "=r" (i) : "rm" (n));
+	return i;
+
+#else
+	uint32_t i = 0;
+
+	if ((n & UINT32_C(0xFFFF0000)) == 0) {
+		n <<= 16;
+		i = 16;
+	}
+
+	if ((n & UINT32_C(0xFF000000)) == 0) {
+		n <<= 8;
+		i += 8;
+	}
+
+	if ((n & UINT32_C(0xF0000000)) == 0) {
+		n <<= 4;
+		i += 4;
+	}
+
+	if ((n & UINT32_C(0xC0000000)) == 0) {
+		n <<= 2;
+		i += 2;
+	}
+
+	if ((n & UINT32_C(0x80000000)) == 0)
+		++i;
+
+	return i;
+#endif
+}
+
+
+static inline uint32_t
+ctz32(uint32_t n)
+{
+#if defined(__INTEL_COMPILER)
+	return _bit_scan_forward(n);
+
+#elif TUKLIB_GNUC_REQ(3, 4) && UINT_MAX >= UINT32_MAX
+	return __builtin_ctz(n);
+
+#elif defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))
+	uint32_t i;
+	__asm__("bsfl %1, %0" : "=r" (i) : "rm" (n));
+	return i;
+
+#else
+	uint32_t i = 0;
+
+	if ((n & UINT32_C(0x0000FFFF)) == 0) {
+		n >>= 16;
+		i = 16;
+	}
+
+	if ((n & UINT32_C(0x000000FF)) == 0) {
+		n >>= 8;
+		i += 8;
+	}
+
+	if ((n & UINT32_C(0x0000000F)) == 0) {
+		n >>= 4;
+		i += 4;
+	}
+
+	if ((n & UINT32_C(0x00000003)) == 0) {
+		n >>= 2;
+		i += 2;
+	}
+
+	if ((n & UINT32_C(0x00000001)) == 0)
+		++i;
+
+	return i;
+#endif
+}
+
+#define bsf32 ctz32
+
+#endif
diff --git a/Utilities/cmliblzma/config.h.in b/Utilities/cmliblzma/config.h.in
new file mode 100644
index 0000000..b197f27
--- /dev/null
+++ b/Utilities/cmliblzma/config.h.in
@@ -0,0 +1,285 @@
+
+/*
+ * Ensure we have C99-style int64_t, etc, all defined.
+ */
+
+/* First, we need to know if the system has already defined them. */
+#cmakedefine HAVE_INT16_T
+#cmakedefine HAVE_INT32_T
+#cmakedefine HAVE_INT64_T
+#cmakedefine HAVE_INTMAX_T
+
+#cmakedefine HAVE_UINT8_T
+#cmakedefine HAVE_UINT16_T
+#cmakedefine HAVE_UINT32_T
+#cmakedefine HAVE_UINT64_T
+#cmakedefine HAVE_UINTMAX_T
+
+/* We might have the types we want under other spellings. */
+#cmakedefine HAVE___INT64
+#cmakedefine HAVE_U_INT64_T
+#cmakedefine HAVE_UNSIGNED___INT64
+
+/* The sizes of various standard integer types. */
+@SIZE_OF_SHORT_CODE@
+@SIZE_OF_INT_CODE@
+@SIZE_OF_LONG_CODE@
+@SIZE_OF_LONG_LONG_CODE@
+@SIZE_OF_UNSIGNED_SHORT_CODE@
+@SIZE_OF_UNSIGNED_CODE@
+@SIZE_OF_UNSIGNED_LONG_CODE@
+@SIZE_OF_UNSIGNED_LONG_LONG_CODE@
+
+/*
+ * If we lack int64_t, define it to the first of __int64, int, long, and long long
+ * that exists and is the right size.
+ */
+#if !defined(HAVE_INT64_T) && defined(HAVE___INT64)
+typedef __int64 int64_t;
+#define HAVE_INT64_T
+#endif
+
+#if !defined(HAVE_INT64_T) && SIZE_OF_INT == 8
+typedef int int64_t;
+#define HAVE_INT64_T
+#endif
+
+#if !defined(HAVE_INT64_T) && SIZE_OF_LONG == 8
+typedef long int64_t;
+#define HAVE_INT64_T
+#endif
+
+#if !defined(HAVE_INT64_T) && SIZE_OF_LONG_LONG == 8
+typedef long long int64_t;
+#define HAVE_INT64_T
+#endif
+
+#if !defined(HAVE_INT64_T)
+#error No 64-bit integer type was found.
+#endif
+
+/*
+ * Similarly for int32_t
+ */
+#if !defined(HAVE_INT32_T) && SIZE_OF_INT == 4
+typedef int int32_t;
+#define HAVE_INT32_T
+#endif
+
+#if !defined(HAVE_INT32_T) && SIZE_OF_LONG == 4
+typedef long int32_t;
+#define HAVE_INT32_T
+#endif
+
+#if !defined(HAVE_INT32_T)
+#error No 32-bit integer type was found.
+#endif
+
+/*
+ * Similarly for int16_t
+ */
+#if !defined(HAVE_INT16_T) && SIZE_OF_INT == 2
+typedef int int16_t;
+#define HAVE_INT16_T
+#endif
+
+#if !defined(HAVE_INT16_T) && SIZE_OF_SHORT == 2
+typedef short int16_t;
+#define HAVE_INT16_T
+#endif
+
+#if !defined(HAVE_INT16_T)
+#error No 16-bit integer type was found.
+#endif
+
+/*
+ * Similarly for uint64_t
+ */
+#if !defined(HAVE_UINT64_T) && defined(HAVE_UNSIGNED___INT64)
+typedef unsigned __int64 uint64_t;
+#define HAVE_UINT64_T
+#endif
+
+#if !defined(HAVE_UINT64_T) && SIZE_OF_UNSIGNED == 8
+typedef unsigned uint64_t;
+#define HAVE_UINT64_T
+#endif
+
+#if !defined(HAVE_UINT64_T) && SIZE_OF_UNSIGNED_LONG == 8
+typedef unsigned long uint64_t;
+#define HAVE_UINT64_T
+#endif
+
+#if !defined(HAVE_UINT64_T) && SIZE_OF_UNSIGNED_LONG_LONG == 8
+typedef unsigned long long uint64_t;
+#define HAVE_UINT64_T
+#endif
+
+#if !defined(HAVE_UINT64_T)
+#error No 64-bit unsigned integer type was found.
+#endif
+
+/*
+ * Similarly for uint32_t
+ */
+#if !defined(HAVE_UINT32_T) && SIZE_OF_UNSIGNED == 4
+typedef unsigned uint32_t;
+#define HAVE_UINT32_T
+#endif
+
+#if !defined(HAVE_UINT32_T) && SIZE_OF_UNSIGNED_LONG == 4
+typedef unsigned long uint32_t;
+#define HAVE_UINT32_T
+#endif
+
+#if !defined(HAVE_UINT32_T)
+#error No 32-bit unsigned integer type was found.
+#endif
+
+/*
+ * Similarly for uint16_t
+ */
+#if !defined(HAVE_UINT16_T) && SIZE_OF_UNSIGNED == 2
+typedef unsigned uint16_t;
+#define HAVE_UINT16_T
+#endif
+
+#if !defined(HAVE_UINT16_T) && SIZE_OF_UNSIGNED_SHORT == 2
+typedef unsigned short uint16_t;
+#define HAVE_UINT16_T
+#endif
+
+#if !defined(HAVE_UINT16_T)
+#error No 16-bit unsigned integer type was found.
+#endif
+
+/*
+ * Similarly for uint8_t
+ */
+#if !defined(HAVE_UINT8_T)
+typedef unsigned char uint8_t;
+#define HAVE_UINT8_T
+#endif
+
+#if !defined(HAVE_UINT16_T)
+#error No 8-bit unsigned integer type was found.
+#endif
+
+/* Define intmax_t and uintmax_t if they are not already defined. */
+#if !defined(HAVE_INTMAX_T)
+typedef int64_t intmax_t;
+#define INTMAX_MIN INT64_MIN
+#define INTMAX_MAX INT64_MAX
+#endif
+
+#if !defined(HAVE_UINTMAX_T)
+typedef uint64_t uintmax_t;
+#endif
+
+
+#cmakedefine uintptr_t @uintptr_t@
+
+
+#cmakedefine HAVE_RESTRICT
+#cmakedefine HAVE___RESTRICT
+
+#cmakedefine HAVE_INLINE
+#cmakedefine HAVE___INLINE
+
+#ifndef HAVE_RESTRICT
+#  ifdef HAVE___RESTRICT
+#    define LZMA_RESTRICT __restrict
+#  else
+#    define LZMA_RESTRICT
+#  endif
+#else
+#  define LZMA_RESTRICT restrict
+#endif /* HAVE_RESTRICT */
+
+#ifndef HAVE_INLINE
+#  ifdef HAVE___INLINE
+#    define inline __inline
+#  else
+#    define inline
+#  endif
+#endif /* HAVE_INLINE */
+
+
+#cmakedefine WORDS_BIGENDIAN 1
+
+#cmakedefine HAVE_BYTESWAP_H 1
+#cmakedefine HAVE_BSWAP_16 1
+#cmakedefine HAVE_BSWAP_32 1
+#cmakedefine HAVE_BSWAP_64 1
+
+
+#define HAVE_CHECK_CRC32 1
+#define HAVE_CHECK_CRC64 1
+#define HAVE_CHECK_SHA256 1
+
+#define HAVE_DECODER_ARM 1
+#define HAVE_DECODER_ARMTHUMB 1
+#define HAVE_DECODER_DELTA 1
+#define HAVE_DECODER_IA64 1
+#define HAVE_DECODER_LZMA1 1
+#define HAVE_DECODER_LZMA2 1
+#define HAVE_DECODER_POWERPC 1
+#define HAVE_DECODER_SPARC 1
+#define HAVE_DECODER_X86 1
+
+#define HAVE_ENCODER_ARM 1
+#define HAVE_ENCODER_ARMTHUMB 1
+#define HAVE_ENCODER_DELTA 1
+#define HAVE_ENCODER_IA64 1
+#define HAVE_ENCODER_LZMA1 1
+#define HAVE_ENCODER_LZMA2 1
+#define HAVE_ENCODER_POWERPC 1
+#define HAVE_ENCODER_SPARC 1
+#define HAVE_ENCODER_X86 1
+
+#define HAVE_MF_BT2 1
+#define HAVE_MF_BT3 1
+#define HAVE_MF_BT4 1
+#define HAVE_MF_HC3 1
+#define HAVE_MF_HC4 1
+
+/* Define to 1 if you have the <inttypes.h> header file. */
+#cmakedefine HAVE_INTTYPES_H 1
+
+/* Define to 1 if you have the <limits.h> header file. */
+#cmakedefine HAVE_LIMITS_H 1
+
+/* Define to 1 if you have the <memory.h> header file. */
+#cmakedefine HAVE_MEMORY_H 1
+
+/* Define to 1 if stdbool.h conforms to C99. */
+#cmakedefine HAVE_STDBOOL_H 1
+
+/* Define to 1 if you have the <stdint.h> header file. */
+#cmakedefine HAVE_STDINT_H 1
+
+/* Define to 1 if you have the <strings.h> header file. */
+#cmakedefine HAVE_STRINGS_H 1
+
+/* Define to 1 if you have the <string.h> header file. */
+#cmakedefine HAVE_STRING_H 1
+
+/* Define to 1 if you have the <sys/byteorder.h> header file. */
+#cmakedefine HAVE_SYS_BYTEORDER_H 1
+
+/* Define to 1 if you have the <sys/endian.h> header file. */
+#cmakedefine HAVE_SYS_ENDIAN_H 1
+
+/* Define to 1 or 0, depending whether the compiler supports simple visibility
+   declarations. */
+#cmakedefine HAVE_VISIBILITY 1
+
+/* Define to 1 if the system has the type `_Bool'. */
+#cmakedefine HAVE__BOOL 1
+
+/* The size of `size_t', as computed by sizeof. */
+#cmakedefine SIZEOF_SIZE_T @SIZEOF_SIZE_T@
+
+/* Define to 1 if the system supports fast unaligned access to 16-bit and
+   32-bit integers. */
+#define TUKLIB_FAST_UNALIGNED_ACCESS 1
diff --git a/Utilities/cmliblzma/liblzma/api/lzma.h b/Utilities/cmliblzma/liblzma/api/lzma.h
new file mode 100644
index 0000000..fb874c3
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/api/lzma.h
@@ -0,0 +1,313 @@
+/**
+ * \file        api/lzma.h
+ * \brief       The public API of liblzma data compression library
+ *
+ * liblzma is a public domain general-purpose data compression library with
+ * a zlib-like API. The native file format is .xz, but also the old .lzma
+ * format and raw (no headers) streams are supported. Multiple compression
+ * algorithms (filters) are supported. Currently LZMA2 is the primary filter.
+ *
+ * liblzma is part of XZ Utils <http://tukaani.org/xz/>. XZ Utils includes
+ * a gzip-like command line tool named xz and some other tools. XZ Utils
+ * is developed and maintained by Lasse Collin.
+ *
+ * Major parts of liblzma are based on Igor Pavlov's public domain LZMA SDK
+ * <http://7-zip.org/sdk.html>.
+ *
+ * The SHA-256 implementation is based on the public domain code found from
+ * 7-Zip <http://7-zip.org/>, which has a modified version of the public
+ * domain SHA-256 code found from Crypto++ <http://www.cryptopp.com/>.
+ * The SHA-256 code in Crypto++ was written by Kevin Springle and Wei Dai.
+ */
+
+/*
+ * Author: Lasse Collin
+ *
+ * This file has been put into the public domain.
+ * You can do whatever you want with this file.
+ */
+
+#ifndef LZMA_H
+#define LZMA_H
+
+/*****************************
+ * Required standard headers *
+ *****************************/
+
+/*
+ * liblzma API headers need some standard types and macros. To allow
+ * including lzma.h without requiring the application to include other
+ * headers first, lzma.h includes the required standard headers unless
+ * they already seem to be included already or if LZMA_MANUAL_HEADERS
+ * has been defined.
+ *
+ * Here's what types and macros are needed and from which headers:
+ *  - stddef.h: size_t, NULL
+ *  - stdint.h: uint8_t, uint32_t, uint64_t, UINT32_C(n), uint64_C(n),
+ *    UINT32_MAX, UINT64_MAX
+ *
+ * However, inttypes.h is a little more portable than stdint.h, although
+ * inttypes.h declares some unneeded things compared to plain stdint.h.
+ *
+ * The hacks below aren't perfect, specifically they assume that inttypes.h
+ * exists and that it typedefs at least uint8_t, uint32_t, and uint64_t,
+ * and that, in case of incomplete inttypes.h, unsigned int is 32-bit.
+ * If the application already takes care of setting up all the types and
+ * macros properly (for example by using gnulib's stdint.h or inttypes.h),
+ * we try to detect that the macros are already defined and don't include
+ * inttypes.h here again. However, you may define LZMA_MANUAL_HEADERS to
+ * force this file to never include any system headers.
+ *
+ * Some could argue that liblzma API should provide all the required types,
+ * for example lzma_uint64, LZMA_UINT64_C(n), and LZMA_UINT64_MAX. This was
+ * seen as an unnecessary mess, since most systems already provide all the
+ * necessary types and macros in the standard headers.
+ *
+ * Note that liblzma API still has lzma_bool, because using stdbool.h would
+ * break C89 and C++ programs on many systems. sizeof(bool) in C99 isn't
+ * necessarily the same as sizeof(bool) in C++.
+ */
+
+#ifndef LZMA_MANUAL_HEADERS
+	/*
+	 * I suppose this works portably also in C++. Note that in C++,
+	 * we need to get size_t into the global namespace.
+	 */
+#	include <stddef.h>
+
+	/*
+	 * Skip inttypes.h if we already have all the required macros. If we
+	 * have the macros, we assume that we have the matching typedefs too.
+	 */
+#	if !defined(UINT32_C) || !defined(UINT64_C) \
+			|| !defined(UINT32_MAX) || !defined(UINT64_MAX)
+		/*
+		 * MSVC has no C99 support, and thus it cannot be used to
+		 * compile liblzma. The liblzma API has to still be usable
+		 * from MSVC, so we need to define the required standard
+		 * integer types here.
+		 */
+#		if defined(_WIN32) && defined(_MSC_VER)
+			typedef unsigned __int8 uint8_t;
+			typedef unsigned __int32 uint32_t;
+			typedef unsigned __int64 uint64_t;
+#		else
+			/* Use the standard inttypes.h. */
+#			ifdef __cplusplus
+				/*
+				 * C99 sections 7.18.2 and 7.18.4 specify
+				 * that C++ implementations define the limit
+				 * and constant macros only if specifically
+				 * requested. Note that if you want the
+				 * format macros (PRIu64 etc.) too, you need
+				 * to define __STDC_FORMAT_MACROS before
+				 * including lzma.h, since re-including
+				 * inttypes.h with __STDC_FORMAT_MACROS
+				 * defined doesn't necessarily work.
+				 */
+#				ifndef __STDC_LIMIT_MACROS
+#					define __STDC_LIMIT_MACROS 1
+#				endif
+#				ifndef __STDC_CONSTANT_MACROS
+#					define __STDC_CONSTANT_MACROS 1
+#				endif
+#			endif
+
+#			include <inttypes.h>
+#		endif
+
+		/*
+		 * Some old systems have only the typedefs in inttypes.h, and
+		 * lack all the macros. For those systems, we need a few more
+		 * hacks. We assume that unsigned int is 32-bit and unsigned
+		 * long is either 32-bit or 64-bit. If these hacks aren't
+		 * enough, the application has to setup the types manually
+		 * before including lzma.h.
+		 */
+#		ifndef UINT32_C
+#			if defined(_WIN32) && defined(_MSC_VER)
+#				define UINT32_C(n) n ## UI32
+#			else
+#				define UINT32_C(n) n ## U
+#			endif
+#		endif
+
+#		ifndef UINT64_C
+#			if defined(_WIN32) && defined(_MSC_VER)
+#				define UINT64_C(n) n ## UI64
+#			else
+				/* Get ULONG_MAX. */
+#				include <limits.h>
+#				if ULONG_MAX == 4294967295UL
+#					define UINT64_C(n) n ## ULL
+#				else
+#					define UINT64_C(n) n ## UL
+#				endif
+#			endif
+#		endif
+
+#		ifndef UINT32_MAX
+#			define UINT32_MAX (UINT32_C(4294967295))
+#		endif
+
+#		ifndef UINT64_MAX
+#			define UINT64_MAX (UINT64_C(18446744073709551615))
+#		endif
+#	endif
+#endif /* ifdef LZMA_MANUAL_HEADERS */
+
+
+/******************
+ * LZMA_API macro *
+ ******************/
+
+/*
+ * Some systems require that the functions and function pointers are
+ * declared specially in the headers. LZMA_API_IMPORT is for importing
+ * symbols and LZMA_API_CALL is to specify the calling convention.
+ *
+ * By default it is assumed that the application will link dynamically
+ * against liblzma. #define LZMA_API_STATIC in your application if you
+ * want to link against static liblzma. If you don't care about portability
+ * to operating systems like Windows, or at least don't care about linking
+ * against static liblzma on them, don't worry about LZMA_API_STATIC. That
+ * is, most developers will never need to use LZMA_API_STATIC.
+ *
+ * The GCC variants are a special case on Windows (Cygwin and MinGW).
+ * We rely on GCC doing the right thing with its auto-import feature,
+ * and thus don't use __declspec(dllimport). This way developers don't
+ * need to worry about LZMA_API_STATIC. Also the calling convention is
+ * omitted on Cygwin but not on MinGW.
+ */
+#ifndef LZMA_API_IMPORT
+#	if !defined(LZMA_API_STATIC) && defined(_WIN32) && !defined(__GNUC__)
+#		define LZMA_API_IMPORT __declspec(dllimport)
+#	else
+#		define LZMA_API_IMPORT
+#	endif
+#endif
+
+#ifndef LZMA_API_CALL
+#	if defined(_WIN32) && !defined(__CYGWIN__)
+#		define LZMA_API_CALL __cdecl
+#	else
+#		define LZMA_API_CALL
+#	endif
+#endif
+
+#ifndef LZMA_API
+#	define LZMA_API(type) LZMA_API_IMPORT type LZMA_API_CALL
+#endif
+
+
+/***********
+ * nothrow *
+ ***********/
+
+/*
+ * None of the functions in liblzma may throw an exception. Even
+ * the functions that use callback functions won't throw exceptions,
+ * because liblzma would break if a callback function threw an exception.
+ */
+#ifndef lzma_nothrow
+#	if defined(__cplusplus)
+#		define lzma_nothrow throw()
+#	elif __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 3)
+#		define lzma_nothrow __attribute__((__nothrow__))
+#	else
+#		define lzma_nothrow
+#	endif
+#endif
+
+
+/********************
+ * GNU C extensions *
+ ********************/
+
+/*
+ * GNU C extensions are used conditionally in the public API. It doesn't
+ * break anything if these are sometimes enabled and sometimes not, only
+ * affects warnings and optimizations.
+ */
+#if __GNUC__ >= 3
+#	ifndef lzma_attribute
+#		define lzma_attribute(attr) __attribute__(attr)
+#	endif
+
+	/* warn_unused_result was added in GCC 3.4. */
+#	ifndef lzma_attr_warn_unused_result
+#		if __GNUC__ == 3 && __GNUC_MINOR__ < 4
+#			define lzma_attr_warn_unused_result
+#		endif
+#	endif
+
+#else
+#	ifndef lzma_attribute
+#		define lzma_attribute(attr)
+#	endif
+#endif
+
+
+#ifndef lzma_attr_pure
+#	define lzma_attr_pure lzma_attribute((__pure__))
+#endif
+
+#ifndef lzma_attr_const
+#	define lzma_attr_const lzma_attribute((__const__))
+#endif
+
+#ifndef lzma_attr_warn_unused_result
+#	define lzma_attr_warn_unused_result \
+		lzma_attribute((__warn_unused_result__))
+#endif
+
+
+/**************
+ * Subheaders *
+ **************/
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * Subheaders check that this is defined. It is to prevent including
+ * them directly from applications.
+ */
+#define LZMA_H_INTERNAL 1
+
+/* Basic features */
+#include "lzma/version.h"
+#include "lzma/base.h"
+#include "lzma/vli.h"
+#include "lzma/check.h"
+
+/* Filters */
+#include "lzma/filter.h"
+#include "lzma/bcj.h"
+#include "lzma/delta.h"
+#include "lzma/lzma.h"
+
+/* Container formats */
+#include "lzma/container.h"
+
+/* Advanced features */
+#include "lzma/stream_flags.h"
+#include "lzma/block.h"
+#include "lzma/index.h"
+#include "lzma/index_hash.h"
+
+/* Hardware information */
+#include "lzma/hardware.h"
+
+/*
+ * All subheaders included. Undefine LZMA_H_INTERNAL to prevent applications
+ * re-including the subheaders.
+ */
+#undef LZMA_H_INTERNAL
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* ifndef LZMA_H */
diff --git a/Utilities/cmliblzma/liblzma/api/lzma/base.h b/Utilities/cmliblzma/liblzma/api/lzma/base.h
new file mode 100644
index 0000000..43dde8d
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/api/lzma/base.h
@@ -0,0 +1,601 @@
+/**
+ * \file        lzma/base.h
+ * \brief       Data types and functions used in many places in liblzma API
+ */
+
+/*
+ * Author: Lasse Collin
+ *
+ * This file has been put into the public domain.
+ * You can do whatever you want with this file.
+ *
+ * See ../lzma.h for information about liblzma as a whole.
+ */
+
+#ifndef LZMA_H_INTERNAL
+#	error Never include this file directly. Use <lzma.h> instead.
+#endif
+
+
+/**
+ * \brief       Boolean
+ *
+ * This is here because C89 doesn't have stdbool.h. To set a value for
+ * variables having type lzma_bool, you can use
+ *   - C99's `true' and `false' from stdbool.h;
+ *   - C++'s internal `true' and `false'; or
+ *   - integers one (true) and zero (false).
+ */
+typedef unsigned char lzma_bool;
+
+
+/**
+ * \brief       Type of reserved enumeration variable in structures
+ *
+ * To avoid breaking library ABI when new features are added, several
+ * structures contain extra variables that may be used in future. Since
+ * sizeof(enum) can be different than sizeof(int), and sizeof(enum) may
+ * even vary depending on the range of enumeration constants, we specify
+ * a separate type to be used for reserved enumeration variables. All
+ * enumeration constants in liblzma API will be non-negative and less
+ * than 128, which should guarantee that the ABI won't break even when
+ * new constants are added to existing enumerations.
+ */
+typedef enum {
+	LZMA_RESERVED_ENUM      = 0
+} lzma_reserved_enum;
+
+
+/**
+ * \brief       Return values used by several functions in liblzma
+ *
+ * Check the descriptions of specific functions to find out which return
+ * values they can return. With some functions the return values may have
+ * more specific meanings than described here; those differences are
+ * described per-function basis.
+ */
+typedef enum {
+	LZMA_OK                 = 0,
+		/**<
+		 * \brief       Operation completed successfully
+		 */
+
+	LZMA_STREAM_END         = 1,
+		/**<
+		 * \brief       End of stream was reached
+		 *
+		 * In encoder, LZMA_SYNC_FLUSH, LZMA_FULL_FLUSH, or
+		 * LZMA_FINISH was finished. In decoder, this indicates
+		 * that all the data was successfully decoded.
+		 *
+		 * In all cases, when LZMA_STREAM_END is returned, the last
+		 * output bytes should be picked from strm->next_out.
+		 */
+
+	LZMA_NO_CHECK           = 2,
+		/**<
+		 * \brief       Input stream has no integrity check
+		 *
+		 * This return value can be returned only if the
+		 * LZMA_TELL_NO_CHECK flag was used when initializing
+		 * the decoder. LZMA_NO_CHECK is just a warning, and
+		 * the decoding can be continued normally.
+		 *
+		 * It is possible to call lzma_get_check() immediately after
+		 * lzma_code has returned LZMA_NO_CHECK. The result will
+		 * naturally be LZMA_CHECK_NONE, but the possibility to call
+		 * lzma_get_check() may be convenient in some applications.
+		 */
+
+	LZMA_UNSUPPORTED_CHECK  = 3,
+		/**<
+		 * \brief       Cannot calculate the integrity check
+		 *
+		 * The usage of this return value is different in encoders
+		 * and decoders.
+		 *
+		 * Encoders can return this value only from the initialization
+		 * function. If initialization fails with this value, the
+		 * encoding cannot be done, because there's no way to produce
+		 * output with the correct integrity check.
+		 *
+		 * Decoders can return this value only from lzma_code() and
+		 * only if the LZMA_TELL_UNSUPPORTED_CHECK flag was used when
+		 * initializing the decoder. The decoding can still be
+		 * continued normally even if the check type is unsupported,
+		 * but naturally the check will not be validated, and possible
+		 * errors may go undetected.
+		 *
+		 * With decoder, it is possible to call lzma_get_check()
+		 * immediately after lzma_code() has returned
+		 * LZMA_UNSUPPORTED_CHECK. This way it is possible to find
+		 * out what the unsupported Check ID was.
+		 */
+
+	LZMA_GET_CHECK          = 4,
+		/**<
+		 * \brief       Integrity check type is now available
+		 *
+		 * This value can be returned only by the lzma_code() function
+		 * and only if the decoder was initialized with the
+		 * LZMA_TELL_ANY_CHECK flag. LZMA_GET_CHECK tells the
+		 * application that it may now call lzma_get_check() to find
+		 * out the Check ID. This can be used, for example, to
+		 * implement a decoder that accepts only files that have
+		 * strong enough integrity check.
+		 */
+
+	LZMA_MEM_ERROR          = 5,
+		/**<
+		 * \brief       Cannot allocate memory
+		 *
+		 * Memory allocation failed, or the size of the allocation
+		 * would be greater than SIZE_MAX.
+		 *
+		 * Due to internal implementation reasons, the coding cannot
+		 * be continued even if more memory were made available after
+		 * LZMA_MEM_ERROR.
+		 */
+
+	LZMA_MEMLIMIT_ERROR     = 6,
+		/**
+		 * \brief       Memory usage limit was reached
+		 *
+		 * Decoder would need more memory than allowed by the
+		 * specified memory usage limit. To continue decoding,
+		 * the memory usage limit has to be increased with
+		 * lzma_memlimit_set().
+		 */
+
+	LZMA_FORMAT_ERROR       = 7,
+		/**<
+		 * \brief       File format not recognized
+		 *
+		 * The decoder did not recognize the input as supported file
+		 * format. This error can occur, for example, when trying to
+		 * decode .lzma format file with lzma_stream_decoder,
+		 * because lzma_stream_decoder accepts only the .xz format.
+		 */
+
+	LZMA_OPTIONS_ERROR      = 8,
+		/**<
+		 * \brief       Invalid or unsupported options
+		 *
+		 * Invalid or unsupported options, for example
+		 *  - unsupported filter(s) or filter options; or
+		 *  - reserved bits set in headers (decoder only).
+		 *
+		 * Rebuilding liblzma with more features enabled, or
+		 * upgrading to a newer version of liblzma may help.
+		 */
+
+	LZMA_DATA_ERROR         = 9,
+		/**<
+		 * \brief       Data is corrupt
+		 *
+		 * The usage of this return value is different in encoders
+		 * and decoders. In both encoder and decoder, the coding
+		 * cannot continue after this error.
+		 *
+		 * Encoders return this if size limits of the target file
+		 * format would be exceeded. These limits are huge, thus
+		 * getting this error from an encoder is mostly theoretical.
+		 * For example, the maximum compressed and uncompressed
+		 * size of a .xz Stream is roughly 8 EiB (2^63 bytes).
+		 *
+		 * Decoders return this error if the input data is corrupt.
+		 * This can mean, for example, invalid CRC32 in headers
+		 * or invalid check of uncompressed data.
+		 */
+
+	LZMA_BUF_ERROR          = 10,
+		/**<
+		 * \brief       No progress is possible
+		 *
+		 * This error code is returned when the coder cannot consume
+		 * any new input and produce any new output. The most common
+		 * reason for this error is that the input stream being
+		 * decoded is truncated or corrupt.
+		 *
+		 * This error is not fatal. Coding can be continued normally
+		 * by providing more input and/or more output space, if
+		 * possible.
+		 *
+		 * Typically the first call to lzma_code() that can do no
+		 * progress returns LZMA_OK instead of LZMA_BUF_ERROR. Only
+		 * the second consecutive call doing no progress will return
+		 * LZMA_BUF_ERROR. This is intentional.
+		 *
+		 * With zlib, Z_BUF_ERROR may be returned even if the
+		 * application is doing nothing wrong, so apps will need
+		 * to handle Z_BUF_ERROR specially. The above hack
+		 * guarantees that liblzma never returns LZMA_BUF_ERROR
+		 * to properly written applications unless the input file
+		 * is truncated or corrupt. This should simplify the
+		 * applications a little.
+		 */
+
+	LZMA_PROG_ERROR         = 11,
+		/**<
+		 * \brief       Programming error
+		 *
+		 * This indicates that the arguments given to the function are
+		 * invalid or the internal state of the decoder is corrupt.
+		 *   - Function arguments are invalid or the structures
+		 *     pointed by the argument pointers are invalid
+		 *     e.g. if strm->next_out has been set to NULL and
+		 *     strm->avail_out > 0 when calling lzma_code().
+		 *   - lzma_* functions have been called in wrong order
+		 *     e.g. lzma_code() was called right after lzma_end().
+		 *   - If errors occur randomly, the reason might be flaky
+		 *     hardware.
+		 *
+		 * If you think that your code is correct, this error code
+		 * can be a sign of a bug in liblzma. See the documentation
+		 * how to report bugs.
+		 */
+} lzma_ret;
+
+
+/**
+ * \brief       The `action' argument for lzma_code()
+ *
+ * After the first use of LZMA_SYNC_FLUSH, LZMA_FULL_FLUSH, or LZMA_FINISH,
+ * the same `action' must is used until lzma_code() returns LZMA_STREAM_END.
+ * Also, the amount of input (that is, strm->avail_in) must not be modified
+ * by the application until lzma_code() returns LZMA_STREAM_END. Changing the
+ * `action' or modifying the amount of input will make lzma_code() return
+ * LZMA_PROG_ERROR.
+ */
+typedef enum {
+	LZMA_RUN = 0,
+		/**<
+		 * \brief       Continue coding
+		 *
+		 * Encoder: Encode as much input as possible. Some internal
+		 * buffering will probably be done (depends on the filter
+		 * chain in use), which causes latency: the input used won't
+		 * usually be decodeable from the output of the same
+		 * lzma_code() call.
+		 *
+		 * Decoder: Decode as much input as possible and produce as
+		 * much output as possible.
+		 */
+
+	LZMA_SYNC_FLUSH = 1,
+		/**<
+		 * \brief       Make all the input available at output
+		 *
+		 * Normally the encoder introduces some latency.
+		 * LZMA_SYNC_FLUSH forces all the buffered data to be
+		 * available at output without resetting the internal
+		 * state of the encoder. This way it is possible to use
+		 * compressed stream for example for communication over
+		 * network.
+		 *
+		 * Only some filters support LZMA_SYNC_FLUSH. Trying to use
+		 * LZMA_SYNC_FLUSH with filters that don't support it will
+		 * make lzma_code() return LZMA_OPTIONS_ERROR. For example,
+		 * LZMA1 doesn't support LZMA_SYNC_FLUSH but LZMA2 does.
+		 *
+		 * Using LZMA_SYNC_FLUSH very often can dramatically reduce
+		 * the compression ratio. With some filters (for example,
+		 * LZMA2), fine-tuning the compression options may help
+		 * mitigate this problem significantly (for example,
+		 * match finder with LZMA2).
+		 *
+		 * Decoders don't support LZMA_SYNC_FLUSH.
+		 */
+
+	LZMA_FULL_FLUSH = 2,
+		/**<
+		 * \brief       Finish encoding of the current Block
+		 *
+		 * All the input data going to the current Block must have
+		 * been given to the encoder (the last bytes can still be
+		 * pending in* next_in). Call lzma_code() with LZMA_FULL_FLUSH
+		 * until it returns LZMA_STREAM_END. Then continue normally
+		 * with LZMA_RUN or finish the Stream with LZMA_FINISH.
+		 *
+		 * This action is currently supported only by Stream encoder
+		 * and easy encoder (which uses Stream encoder). If there is
+		 * no unfinished Block, no empty Block is created.
+		 */
+
+	LZMA_FINISH = 3
+		/**<
+		 * \brief       Finish the coding operation
+		 *
+		 * All the input data must have been given to the encoder
+		 * (the last bytes can still be pending in next_in).
+		 * Call lzma_code() with LZMA_FINISH until it returns
+		 * LZMA_STREAM_END. Once LZMA_FINISH has been used,
+		 * the amount of input must no longer be changed by
+		 * the application.
+		 *
+		 * When decoding, using LZMA_FINISH is optional unless the
+		 * LZMA_CONCATENATED flag was used when the decoder was
+		 * initialized. When LZMA_CONCATENATED was not used, the only
+		 * effect of LZMA_FINISH is that the amount of input must not
+		 * be changed just like in the encoder.
+		 */
+} lzma_action;
+
+
+/**
+ * \brief       Custom functions for memory handling
+ *
+ * A pointer to lzma_allocator may be passed via lzma_stream structure
+ * to liblzma, and some advanced functions take a pointer to lzma_allocator
+ * as a separate function argument. The library will use the functions
+ * specified in lzma_allocator for memory handling instead of the default
+ * malloc() and free(). C++ users should note that the custom memory
+ * handling functions must not throw exceptions.
+ *
+ * liblzma doesn't make an internal copy of lzma_allocator. Thus, it is
+ * OK to change these function pointers in the middle of the coding
+ * process, but obviously it must be done carefully to make sure that the
+ * replacement `free' can deallocate memory allocated by the earlier
+ * `alloc' function(s).
+ */
+typedef struct {
+	/**
+	 * \brief       Pointer to a custom memory allocation function
+	 *
+	 * If you don't want a custom allocator, but still want
+	 * custom free(), set this to NULL and liblzma will use
+	 * the standard malloc().
+	 *
+	 * \param       opaque  lzma_allocator.opaque (see below)
+	 * \param       nmemb   Number of elements like in calloc(). liblzma
+	 *                      will always set nmemb to 1, so it is safe to
+	 *                      ignore nmemb in a custom allocator if you like.
+	 *                      The nmemb argument exists only for
+	 *                      compatibility with zlib and libbzip2.
+	 * \param       size    Size of an element in bytes.
+	 *                      liblzma never sets this to zero.
+	 *
+	 * \return      Pointer to the beginning of a memory block of
+	 *              `size' bytes, or NULL if allocation fails
+	 *              for some reason. When allocation fails, functions
+	 *              of liblzma return LZMA_MEM_ERROR.
+	 *
+	 * The allocator should not waste time zeroing the allocated buffers.
+	 * This is not only about speed, but also memory usage, since the
+	 * operating system kernel doesn't necessarily allocate the requested
+	 * memory in physical memory until it is actually used. With small
+	 * input files, liblzma may actually need only a fraction of the
+	 * memory that it requested for allocation.
+	 *
+	 * \note        LZMA_MEM_ERROR is also used when the size of the
+	 *              allocation would be greater than SIZE_MAX. Thus,
+	 *              don't assume that the custom allocator must have
+	 *              returned NULL if some function from liblzma
+	 *              returns LZMA_MEM_ERROR.
+	 */
+	void *(LZMA_API_CALL *alloc)(void *opaque, size_t nmemb, size_t size);
+
+	/**
+	 * \brief       Pointer to a custom memory freeing function
+	 *
+	 * If you don't want a custom freeing function, but still
+	 * want a custom allocator, set this to NULL and liblzma
+	 * will use the standard free().
+	 *
+	 * \param       opaque  lzma_allocator.opaque (see below)
+	 * \param       ptr     Pointer returned by lzma_allocator.alloc(),
+	 *                      or when it is set to NULL, a pointer returned
+	 *                      by the standard malloc().
+	 */
+	void (LZMA_API_CALL *free)(void *opaque, void *ptr);
+
+	/**
+	 * \brief       Pointer passed to .alloc() and .free()
+	 *
+	 * opaque is passed as the first argument to lzma_allocator.alloc()
+	 * and lzma_allocator.free(). This intended to ease implementing
+	 * custom memory allocation functions for use with liblzma.
+	 *
+	 * If you don't need this, you should set this to NULL.
+	 */
+	void *opaque;
+
+} lzma_allocator;
+
+
+/**
+ * \brief       Internal data structure
+ *
+ * The contents of this structure is not visible outside the library.
+ */
+typedef struct lzma_internal_s lzma_internal;
+
+
+/**
+ * \brief       Passing data to and from liblzma
+ *
+ * The lzma_stream structure is used for
+ *  - passing pointers to input and output buffers to liblzma;
+ *  - defining custom memory hander functions; and
+ *  - holding a pointer to coder-specific internal data structures.
+ *
+ * Typical usage:
+ *
+ *  - After allocating lzma_stream (on stack or with malloc()), it must be
+ *    initialized to LZMA_STREAM_INIT (see LZMA_STREAM_INIT for details).
+ *
+ *  - Initialize a coder to the lzma_stream, for example by using
+ *    lzma_easy_encoder() or lzma_auto_decoder(). Some notes:
+ *      - In contrast to zlib, strm->next_in and strm->next_out are
+ *        ignored by all initialization functions, thus it is safe
+ *        to not initialize them yet.
+ *      - The initialization functions always set strm->total_in and
+ *        strm->total_out to zero.
+ *      - If the initialization function fails, no memory is left allocated
+ *        that would require freeing with lzma_end() even if some memory was
+ *        associated with the lzma_stream structure when the initialization
+ *        function was called.
+ *
+ *  - Use lzma_code() to do the actual work.
+ *
+ *  - Once the coding has been finished, the existing lzma_stream can be
+ *    reused. It is OK to reuse lzma_stream with different initialization
+ *    function without calling lzma_end() first. Old allocations are
+ *    automatically freed.
+ *
+ *  - Finally, use lzma_end() to free the allocated memory. lzma_end() never
+ *    frees the lzma_stream structure itself.
+ *
+ * Application may modify the values of total_in and total_out as it wants.
+ * They are updated by liblzma to match the amount of data read and
+ * written, but aren't used for anything else.
+ */
+typedef struct {
+	const uint8_t *next_in; /**< Pointer to the next input byte. */
+	size_t avail_in;    /**< Number of available input bytes in next_in. */
+	uint64_t total_in;  /**< Total number of bytes read by liblzma. */
+
+	uint8_t *next_out;  /**< Pointer to the next output position. */
+	size_t avail_out;   /**< Amount of free space in next_out. */
+	uint64_t total_out; /**< Total number of bytes written by liblzma. */
+
+	/**
+	 * \brief       Custom memory allocation functions
+	 *
+	 * In most cases this is NULL which makes liblzma use
+	 * the standard malloc() and free().
+	 */
+	lzma_allocator *allocator;
+
+	/** Internal state is not visible to applications. */
+	lzma_internal *internal;
+
+	/*
+	 * Reserved space to allow possible future extensions without
+	 * breaking the ABI. Excluding the initialization of this structure,
+	 * you should not touch these, because the names of these variables
+	 * may change.
+	 */
+	void *reserved_ptr1;
+	void *reserved_ptr2;
+	void *reserved_ptr3;
+	void *reserved_ptr4;
+	uint64_t reserved_int1;
+	uint64_t reserved_int2;
+	size_t reserved_int3;
+	size_t reserved_int4;
+	lzma_reserved_enum reserved_enum1;
+	lzma_reserved_enum reserved_enum2;
+
+} lzma_stream;
+
+
+/**
+ * \brief       Initialization for lzma_stream
+ *
+ * When you declare an instance of lzma_stream, you can immediately
+ * initialize it so that initialization functions know that no memory
+ * has been allocated yet:
+ *
+ *     lzma_stream strm = LZMA_STREAM_INIT;
+ *
+ * If you need to initialize a dynamically allocated lzma_stream, you can use
+ * memset(strm_pointer, 0, sizeof(lzma_stream)). Strictly speaking, this
+ * violates the C standard since NULL may have different internal
+ * representation than zero, but it should be portable enough in practice.
+ * Anyway, for maximum portability, you can use something like this:
+ *
+ *     lzma_stream tmp = LZMA_STREAM_INIT;
+ *     *strm = tmp;
+ */
+#define LZMA_STREAM_INIT \
+	{ NULL, 0, 0, NULL, 0, 0, NULL, NULL, \
+	NULL, NULL, NULL, NULL, 0, 0, 0, 0, \
+	LZMA_RESERVED_ENUM, LZMA_RESERVED_ENUM }
+
+
+/**
+ * \brief       Encode or decode data
+ *
+ * Once the lzma_stream has been successfully initialized (e.g. with
+ * lzma_stream_encoder()), the actual encoding or decoding is done
+ * using this function. The application has to update strm->next_in,
+ * strm->avail_in, strm->next_out, and strm->avail_out to pass input
+ * to and get output from liblzma.
+ *
+ * See the description of the coder-specific initialization function to find
+ * out what `action' values are supported by the coder.
+ */
+extern LZMA_API(lzma_ret) lzma_code(lzma_stream *strm, lzma_action action)
+		lzma_nothrow lzma_attr_warn_unused_result;
+
+
+/**
+ * \brief       Free memory allocated for the coder data structures
+ *
+ * \param       strm    Pointer to lzma_stream that is at least initialized
+ *                      with LZMA_STREAM_INIT.
+ *
+ * After lzma_end(strm), strm->internal is guaranteed to be NULL. No other
+ * members of the lzma_stream structure are touched.
+ *
+ * \note        zlib indicates an error if application end()s unfinished
+ *              stream structure. liblzma doesn't do this, and assumes that
+ *              application knows what it is doing.
+ */
+extern LZMA_API(void) lzma_end(lzma_stream *strm) lzma_nothrow;
+
+
+/**
+ * \brief       Get the memory usage of decoder filter chain
+ *
+ * This function is currently supported only when *strm has been initialized
+ * with a function that takes a memlimit argument. With other functions, you
+ * should use e.g. lzma_raw_encoder_memusage() or lzma_raw_decoder_memusage()
+ * to estimate the memory requirements.
+ *
+ * This function is useful e.g. after LZMA_MEMLIMIT_ERROR to find out how big
+ * the memory usage limit should have been to decode the input. Note that
+ * this may give misleading information if decoding .xz Streams that have
+ * multiple Blocks, because each Block can have different memory requirements.
+ *
+ * \return      How much memory is currently allocated for the filter
+ *              decoders. If no filter chain is currently allocated,
+ *              some non-zero value is still returned, which is less than
+ *              or equal to what any filter chain would indicate as its
+ *              memory requirement.
+ *
+ *              If this function isn't supported by *strm or some other error
+ *              occurs, zero is returned.
+ */
+extern LZMA_API(uint64_t) lzma_memusage(const lzma_stream *strm)
+		lzma_nothrow lzma_attr_pure;
+
+
+/**
+ * \brief       Get the current memory usage limit
+ *
+ * This function is supported only when *strm has been initialized with
+ * a function that takes a memlimit argument.
+ *
+ * \return      On success, the current memory usage limit is returned
+ *              (always non-zero). On error, zero is returned.
+ */
+extern LZMA_API(uint64_t) lzma_memlimit_get(const lzma_stream *strm)
+		lzma_nothrow lzma_attr_pure;
+
+
+/**
+ * \brief       Set the memory usage limit
+ *
+ * This function is supported only when *strm has been initialized with
+ * a function that takes a memlimit argument.
+ *
+ * \return      - LZMA_OK: New memory usage limit successfully set.
+ *              - LZMA_MEMLIMIT_ERROR: The new limit is too small.
+ *                The limit was not changed.
+ *              - LZMA_PROG_ERROR: Invalid arguments, e.g. *strm doesn't
+ *                support memory usage limit or memlimit was zero.
+ */
+extern LZMA_API(lzma_ret) lzma_memlimit_set(
+		lzma_stream *strm, uint64_t memlimit) lzma_nothrow;
diff --git a/Utilities/cmliblzma/liblzma/api/lzma/bcj.h b/Utilities/cmliblzma/liblzma/api/lzma/bcj.h
new file mode 100644
index 0000000..8e37538
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/api/lzma/bcj.h
@@ -0,0 +1,90 @@
+/**
+ * \file        lzma/bcj.h
+ * \brief       Branch/Call/Jump conversion filters
+ */
+
+/*
+ * Author: Lasse Collin
+ *
+ * This file has been put into the public domain.
+ * You can do whatever you want with this file.
+ *
+ * See ../lzma.h for information about liblzma as a whole.
+ */
+
+#ifndef LZMA_H_INTERNAL
+#	error Never include this file directly. Use <lzma.h> instead.
+#endif
+
+
+/* Filter IDs for lzma_filter.id */
+
+#define LZMA_FILTER_X86         LZMA_VLI_C(0x04)
+	/**<
+	 * Filter for x86 binaries
+	 */
+
+#define LZMA_FILTER_POWERPC     LZMA_VLI_C(0x05)
+	/**<
+	 * Filter for Big endian PowerPC binaries
+	 */
+
+#define LZMA_FILTER_IA64        LZMA_VLI_C(0x06)
+	/**<
+	 * Filter for IA-64 (Itanium) binaries.
+	 */
+
+#define LZMA_FILTER_ARM         LZMA_VLI_C(0x07)
+	/**<
+	 * Filter for ARM binaries.
+	 */
+
+#define LZMA_FILTER_ARMTHUMB    LZMA_VLI_C(0x08)
+	/**<
+	 * Filter for ARM-Thumb binaries.
+	 */
+
+#define LZMA_FILTER_SPARC       LZMA_VLI_C(0x09)
+	/**<
+	 * Filter for SPARC binaries.
+	 */
+
+
+/**
+ * \brief       Options for BCJ filters
+ *
+ * The BCJ filters never change the size of the data. Specifying options
+ * for them is optional: if pointer to options is NULL, default value is
+ * used. You probably never need to specify options to BCJ filters, so just
+ * set the options pointer to NULL and be happy.
+ *
+ * If options with non-default values have been specified when encoding,
+ * the same options must also be specified when decoding.
+ *
+ * \note        At the moment, none of the BCJ filters support
+ *              LZMA_SYNC_FLUSH. If LZMA_SYNC_FLUSH is specified,
+ *              LZMA_OPTIONS_ERROR will be returned. If there is need,
+ *              partial support for LZMA_SYNC_FLUSH can be added in future.
+ *              Partial means that flushing would be possible only at
+ *              offsets that are multiple of 2, 4, or 16 depending on
+ *              the filter, except x86 which cannot be made to support
+ *              LZMA_SYNC_FLUSH predictably.
+ */
+typedef struct {
+	/**
+	 * \brief       Start offset for conversions
+	 *
+	 * This setting is useful only when the same filter is used
+	 * _separately_ for multiple sections of the same executable file,
+	 * and the sections contain cross-section branch/call/jump
+	 * instructions. In that case it is beneficial to set the start
+	 * offset of the non-first sections so that the relative addresses
+	 * of the cross-section branch/call/jump instructions will use the
+	 * same absolute addresses as in the first section.
+	 *
+	 * When the pointer to options is NULL, the default value (zero)
+	 * is used.
+	 */
+	uint32_t start_offset;
+
+} lzma_options_bcj;
diff --git a/Utilities/cmliblzma/liblzma/api/lzma/block.h b/Utilities/cmliblzma/liblzma/api/lzma/block.h
new file mode 100644
index 0000000..8a4bf23
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/api/lzma/block.h
@@ -0,0 +1,530 @@
+/**
+ * \file        lzma/block.h
+ * \brief       .xz Block handling
+ */
+
+/*
+ * Author: Lasse Collin
+ *
+ * This file has been put into the public domain.
+ * You can do whatever you want with this file.
+ *
+ * See ../lzma.h for information about liblzma as a whole.
+ */
+
+#ifndef LZMA_H_INTERNAL
+#	error Never include this file directly. Use <lzma.h> instead.
+#endif
+
+
+/**
+ * \brief       Options for the Block and Block Header encoders and decoders
+ *
+ * Different Block handling functions use different parts of this structure.
+ * Some read some members, other functions write, and some do both. Only the
+ * members listed for reading need to be initialized when the specified
+ * functions are called. The members marked for writing will be assigned
+ * new values at some point either by calling the given function or by
+ * later calls to lzma_code().
+ */
+typedef struct {
+	/**
+	 * \brief       Block format version
+	 *
+	 * To prevent API and ABI breakages if new features are needed in
+	 * the Block field, a version number is used to indicate which
+	 * fields in this structure are in use. For now, version must always
+	 * be zero. With non-zero version, most Block related functions will
+	 * return LZMA_OPTIONS_ERROR.
+	 *
+	 * Read by:
+	 *  - All functions that take pointer to lzma_block as argument,
+	 *    including lzma_block_header_decode().
+	 *
+	 * Written by:
+	 *  - lzma_block_header_decode()
+	 */
+	uint32_t version;
+
+	/**
+	 * \brief       Size of the Block Header field
+	 *
+	 * This is always a multiple of four.
+	 *
+	 * Read by:
+	 *  - lzma_block_header_encode()
+	 *  - lzma_block_header_decode()
+	 *  - lzma_block_compressed_size()
+	 *  - lzma_block_unpadded_size()
+	 *  - lzma_block_total_size()
+	 *  - lzma_block_decoder()
+	 *  - lzma_block_buffer_decode()
+	 *
+	 * Written by:
+	 *  - lzma_block_header_size()
+	 *  - lzma_block_buffer_encode()
+	 */
+	uint32_t header_size;
+#	define LZMA_BLOCK_HEADER_SIZE_MIN 8
+#	define LZMA_BLOCK_HEADER_SIZE_MAX 1024
+
+	/**
+	 * \brief       Type of integrity Check
+	 *
+	 * The Check ID is not stored into the Block Header, thus its value
+	 * must be provided also when decoding.
+	 *
+	 * Read by:
+	 *  - lzma_block_header_encode()
+	 *  - lzma_block_header_decode()
+	 *  - lzma_block_compressed_size()
+	 *  - lzma_block_unpadded_size()
+	 *  - lzma_block_total_size()
+	 *  - lzma_block_encoder()
+	 *  - lzma_block_decoder()
+	 *  - lzma_block_buffer_encode()
+	 *  - lzma_block_buffer_decode()
+	 */
+	lzma_check check;
+
+	/**
+	 * \brief       Size of the Compressed Data in bytes
+	 *
+	 * Encoding: If this is not LZMA_VLI_UNKNOWN, Block Header encoder
+	 * will store this value to the Block Header. Block encoder doesn't
+	 * care about this value, but will set it once the encoding has been
+	 * finished.
+	 *
+	 * Decoding: If this is not LZMA_VLI_UNKNOWN, Block decoder will
+	 * verify that the size of the Compressed Data field matches
+	 * compressed_size.
+	 *
+	 * Usually you don't know this value when encoding in streamed mode,
+	 * and thus cannot write this field into the Block Header.
+	 *
+	 * In non-streamed mode you can reserve space for this field before
+	 * encoding the actual Block. After encoding the data, finish the
+	 * Block by encoding the Block Header. Steps in detail:
+	 *
+	 *  - Set compressed_size to some big enough value. If you don't know
+	 *    better, use LZMA_VLI_MAX, but remember that bigger values take
+	 *    more space in Block Header.
+	 *
+	 *  - Call lzma_block_header_size() to see how much space you need to
+	 *    reserve for the Block Header.
+	 *
+	 *  - Encode the Block using lzma_block_encoder() and lzma_code().
+	 *    It sets compressed_size to the correct value.
+	 *
+	 *  - Use lzma_block_header_encode() to encode the Block Header.
+	 *    Because space was reserved in the first step, you don't need
+	 *    to call lzma_block_header_size() anymore, because due to
+	 *    reserving, header_size has to be big enough. If it is "too big",
+	 *    lzma_block_header_encode() will add enough Header Padding to
+	 *    make Block Header to match the size specified by header_size.
+	 *
+	 * Read by:
+	 *  - lzma_block_header_size()
+	 *  - lzma_block_header_encode()
+	 *  - lzma_block_compressed_size()
+	 *  - lzma_block_unpadded_size()
+	 *  - lzma_block_total_size()
+	 *  - lzma_block_decoder()
+	 *  - lzma_block_buffer_decode()
+	 *
+	 * Written by:
+	 *  - lzma_block_header_decode()
+	 *  - lzma_block_compressed_size()
+	 *  - lzma_block_encoder()
+	 *  - lzma_block_decoder()
+	 *  - lzma_block_buffer_encode()
+	 *  - lzma_block_buffer_decode()
+	 */
+	lzma_vli compressed_size;
+
+	/**
+	 * \brief       Uncompressed Size in bytes
+	 *
+	 * This is handled very similarly to compressed_size above.
+	 *
+	 * uncompressed_size is needed by fewer functions than
+	 * compressed_size. This is because uncompressed_size isn't
+	 * needed to validate that Block stays within proper limits.
+	 *
+	 * Read by:
+	 *  - lzma_block_header_size()
+	 *  - lzma_block_header_encode()
+	 *  - lzma_block_decoder()
+	 *  - lzma_block_buffer_decode()
+	 *
+	 * Written by:
+	 *  - lzma_block_header_decode()
+	 *  - lzma_block_encoder()
+	 *  - lzma_block_decoder()
+	 *  - lzma_block_buffer_encode()
+	 *  - lzma_block_buffer_decode()
+	 */
+	lzma_vli uncompressed_size;
+
+	/**
+	 * \brief       Array of filters
+	 *
+	 * There can be 1-4 filters. The end of the array is marked with
+	 * .id = LZMA_VLI_UNKNOWN.
+	 *
+	 * Read by:
+	 *  - lzma_block_header_size()
+	 *  - lzma_block_header_encode()
+	 *  - lzma_block_encoder()
+	 *  - lzma_block_decoder()
+	 *  - lzma_block_buffer_encode()
+	 *  - lzma_block_buffer_decode()
+	 *
+	 * Written by:
+	 *  - lzma_block_header_decode(): Note that this does NOT free()
+	 *    the old filter options structures. All unused filters[] will
+	 *    have .id == LZMA_VLI_UNKNOWN and .options == NULL. If
+	 *    decoding fails, all filters[] are guaranteed to be
+	 *    LZMA_VLI_UNKNOWN and NULL.
+	 *
+	 * \note        Because of the array is terminated with
+	 *              .id = LZMA_VLI_UNKNOWN, the actual array must
+	 *              have LZMA_FILTERS_MAX + 1 members or the Block
+	 *              Header decoder will overflow the buffer.
+	 */
+	lzma_filter *filters;
+
+	/**
+	 * \brief       Raw value stored in the Check field
+	 *
+	 * After successful coding, the first lzma_check_size(check) bytes
+	 * of this array contain the raw value stored in the Check field.
+	 *
+	 * Note that CRC32 and CRC64 are stored in little endian byte order.
+	 * Take it into account if you display the Check values to the user.
+	 *
+	 * Written by:
+	 *  - lzma_block_encoder()
+	 *  - lzma_block_decoder()
+	 *  - lzma_block_buffer_encode()
+	 *  - lzma_block_buffer_decode()
+	 */
+	uint8_t raw_check[LZMA_CHECK_SIZE_MAX];
+
+	/*
+	 * Reserved space to allow possible future extensions without
+	 * breaking the ABI. You should not touch these, because the names
+	 * of these variables may change. These are and will never be used
+	 * with the currently supported options, so it is safe to leave these
+	 * uninitialized.
+	 */
+	void *reserved_ptr1;
+	void *reserved_ptr2;
+	void *reserved_ptr3;
+	uint32_t reserved_int1;
+	uint32_t reserved_int2;
+	lzma_vli reserved_int3;
+	lzma_vli reserved_int4;
+	lzma_vli reserved_int5;
+	lzma_vli reserved_int6;
+	lzma_vli reserved_int7;
+	lzma_vli reserved_int8;
+	lzma_reserved_enum reserved_enum1;
+	lzma_reserved_enum reserved_enum2;
+	lzma_reserved_enum reserved_enum3;
+	lzma_reserved_enum reserved_enum4;
+	lzma_bool reserved_bool1;
+	lzma_bool reserved_bool2;
+	lzma_bool reserved_bool3;
+	lzma_bool reserved_bool4;
+	lzma_bool reserved_bool5;
+	lzma_bool reserved_bool6;
+	lzma_bool reserved_bool7;
+	lzma_bool reserved_bool8;
+
+} lzma_block;
+
+
+/**
+ * \brief       Decode the Block Header Size field
+ *
+ * To decode Block Header using lzma_block_header_decode(), the size of the
+ * Block Header has to be known and stored into lzma_block.header_size.
+ * The size can be calculated from the first byte of a Block using this macro.
+ * Note that if the first byte is 0x00, it indicates beginning of Index; use
+ * this macro only when the byte is not 0x00.
+ *
+ * There is no encoding macro, because Block Header encoder is enough for that.
+ */
+#define lzma_block_header_size_decode(b) (((uint32_t)(b) + 1) * 4)
+
+
+/**
+ * \brief       Calculate Block Header Size
+ *
+ * Calculate the minimum size needed for the Block Header field using the
+ * settings specified in the lzma_block structure. Note that it is OK to
+ * increase the calculated header_size value as long as it is a multiple of
+ * four and doesn't exceed LZMA_BLOCK_HEADER_SIZE_MAX. Increasing header_size
+ * just means that lzma_block_header_encode() will add Header Padding.
+ *
+ * \return      - LZMA_OK: Size calculated successfully and stored to
+ *                block->header_size.
+ *              - LZMA_OPTIONS_ERROR: Unsupported version, filters or
+ *                filter options.
+ *              - LZMA_PROG_ERROR: Invalid values like compressed_size == 0.
+ *
+ * \note        This doesn't check that all the options are valid i.e. this
+ *              may return LZMA_OK even if lzma_block_header_encode() or
+ *              lzma_block_encoder() would fail. If you want to validate the
+ *              filter chain, consider using lzma_memlimit_encoder() which as
+ *              a side-effect validates the filter chain.
+ */
+extern LZMA_API(lzma_ret) lzma_block_header_size(lzma_block *block)
+		lzma_nothrow lzma_attr_warn_unused_result;
+
+
+/**
+ * \brief       Encode Block Header
+ *
+ * The caller must have calculated the size of the Block Header already with
+ * lzma_block_header_size(). If a value larger than the one calculated by
+ * lzma_block_header_size() is used, the Block Header will be padded to the
+ * specified size.
+ *
+ * \param       out         Beginning of the output buffer. This must be
+ *                          at least block->header_size bytes.
+ * \param       block       Block options to be encoded.
+ *
+ * \return      - LZMA_OK: Encoding was successful. block->header_size
+ *                bytes were written to output buffer.
+ *              - LZMA_OPTIONS_ERROR: Invalid or unsupported options.
+ *              - LZMA_PROG_ERROR: Invalid arguments, for example
+ *                block->header_size is invalid or block->filters is NULL.
+ */
+extern LZMA_API(lzma_ret) lzma_block_header_encode(
+		const lzma_block *block, uint8_t *out)
+		lzma_nothrow lzma_attr_warn_unused_result;
+
+
+/**
+ * \brief       Decode Block Header
+ *
+ * block->version should be set to the highest value supported by the
+ * application; currently the only possible version is zero. This function
+ * will set version to the lowest value that still supports all the features
+ * required by the Block Header.
+ *
+ * The size of the Block Header must have already been decoded with
+ * lzma_block_header_size_decode() macro and stored to block->header_size.
+ *
+ * block->filters must have been allocated, but they don't need to be
+ * initialized (possible existing filter options are not freed).
+ *
+ * \param       block       Destination for Block options.
+ * \param       allocator   lzma_allocator for custom allocator functions.
+ *                          Set to NULL to use malloc() (and also free()
+ *                          if an error occurs).
+ * \param       in          Beginning of the input buffer. This must be
+ *                          at least block->header_size bytes.
+ *
+ * \return      - LZMA_OK: Decoding was successful. block->header_size
+ *                bytes were read from the input buffer.
+ *              - LZMA_OPTIONS_ERROR: The Block Header specifies some
+ *                unsupported options such as unsupported filters. This can
+ *                happen also if block->version was set to a too low value
+ *                compared to what would be required to properly represent
+ *                the information stored in the Block Header.
+ *              - LZMA_DATA_ERROR: Block Header is corrupt, for example,
+ *                the CRC32 doesn't match.
+ *              - LZMA_PROG_ERROR: Invalid arguments, for example
+ *                block->header_size is invalid or block->filters is NULL.
+ */
+extern LZMA_API(lzma_ret) lzma_block_header_decode(lzma_block *block,
+		lzma_allocator *allocator, const uint8_t *in)
+		lzma_nothrow lzma_attr_warn_unused_result;
+
+
+/**
+ * \brief       Validate and set Compressed Size according to Unpadded Size
+ *
+ * Block Header stores Compressed Size, but Index has Unpadded Size. If the
+ * application has already parsed the Index and is now decoding Blocks,
+ * it can calculate Compressed Size from Unpadded Size. This function does
+ * exactly that with error checking:
+ *
+ *  - Compressed Size calculated from Unpadded Size must be positive integer,
+ *    that is, Unpadded Size must be big enough that after Block Header and
+ *    Check fields there's still at least one byte for Compressed Size.
+ *
+ *  - If Compressed Size was present in Block Header, the new value
+ *    calculated from Unpadded Size is compared against the value
+ *    from Block Header.
+ *
+ * \note        This function must be called _after_ decoding the Block Header
+ *              field so that it can properly validate Compressed Size if it
+ *              was present in Block Header.
+ *
+ * \return      - LZMA_OK: block->compressed_size was set successfully.
+ *              - LZMA_DATA_ERROR: unpadded_size is too small compared to
+ *                block->header_size and lzma_check_size(block->check).
+ *              - LZMA_PROG_ERROR: Some values are invalid. For example,
+ *                block->header_size must be a multiple of four and
+ *                between 8 and 1024 inclusive.
+ */
+extern LZMA_API(lzma_ret) lzma_block_compressed_size(
+		lzma_block *block, lzma_vli unpadded_size)
+		lzma_nothrow lzma_attr_warn_unused_result;
+
+
+/**
+ * \brief       Calculate Unpadded Size
+ *
+ * The Index field stores Unpadded Size and Uncompressed Size. The latter
+ * can be taken directly from the lzma_block structure after coding a Block,
+ * but Unpadded Size needs to be calculated from Block Header Size,
+ * Compressed Size, and size of the Check field. This is where this function
+ * is needed.
+ *
+ * \return      Unpadded Size on success, or zero on error.
+ */
+extern LZMA_API(lzma_vli) lzma_block_unpadded_size(const lzma_block *block)
+		lzma_nothrow lzma_attr_pure;
+
+
+/**
+ * \brief       Calculate the total encoded size of a Block
+ *
+ * This is equivalent to lzma_block_unpadded_size() except that the returned
+ * value includes the size of the Block Padding field.
+ *
+ * \return      On success, total encoded size of the Block. On error,
+ *              zero is returned.
+ */
+extern LZMA_API(lzma_vli) lzma_block_total_size(const lzma_block *block)
+		lzma_nothrow lzma_attr_pure;
+
+
+/**
+ * \brief       Initialize .xz Block encoder
+ *
+ * Valid actions for lzma_code() are LZMA_RUN, LZMA_SYNC_FLUSH (only if the
+ * filter chain supports it), and LZMA_FINISH.
+ *
+ * \return      - LZMA_OK: All good, continue with lzma_code().
+ *              - LZMA_MEM_ERROR
+ *              - LZMA_OPTIONS_ERROR
+ *              - LZMA_UNSUPPORTED_CHECK: block->check specifies a Check ID
+ *                that is not supported by this buid of liblzma. Initializing
+ *                the encoder failed.
+ *              - LZMA_PROG_ERROR
+ */
+extern LZMA_API(lzma_ret) lzma_block_encoder(
+		lzma_stream *strm, lzma_block *block)
+		lzma_nothrow lzma_attr_warn_unused_result;
+
+
+/**
+ * \brief       Initialize .xz Block decoder
+ *
+ * Valid actions for lzma_code() are LZMA_RUN and LZMA_FINISH. Using
+ * LZMA_FINISH is not required. It is supported only for convenience.
+ *
+ * \return      - LZMA_OK: All good, continue with lzma_code().
+ *              - LZMA_UNSUPPORTED_CHECK: Initialization was successful, but
+ *                the given Check ID is not supported, thus Check will be
+ *                ignored.
+ *              - LZMA_PROG_ERROR
+ *              - LZMA_MEM_ERROR
+ */
+extern LZMA_API(lzma_ret) lzma_block_decoder(
+		lzma_stream *strm, lzma_block *block)
+		lzma_nothrow lzma_attr_warn_unused_result;
+
+
+/**
+ * \brief       Calculate maximum output size for single-call Block encoding
+ *
+ * This is equivalent to lzma_stream_buffer_bound() but for .xz Blocks.
+ * See the documentation of lzma_stream_buffer_bound().
+ */
+extern LZMA_API(size_t) lzma_block_buffer_bound(size_t uncompressed_size)
+		lzma_nothrow;
+
+
+/**
+ * \brief       Single-call .xz Block encoder
+ *
+ * In contrast to the multi-call encoder initialized with
+ * lzma_block_encoder(), this function encodes also the Block Header. This
+ * is required to make it possible to write appropriate Block Header also
+ * in case the data isn't compressible, and different filter chain has to be
+ * used to encode the data in uncompressed form using uncompressed chunks
+ * of the LZMA2 filter.
+ *
+ * When the data isn't compressible, header_size, compressed_size, and
+ * uncompressed_size are set just like when the data was compressible, but
+ * it is possible that header_size is too small to hold the filter chain
+ * specified in block->filters, because that isn't necessarily the filter
+ * chain that was actually used to encode the data. lzma_block_unpadded_size()
+ * still works normally, because it doesn't read the filters array.
+ *
+ * \param       block       Block options: block->version, block->check,
+ *                          and block->filters must have been initialized.
+ * \param       allocator   lzma_allocator for custom allocator functions.
+ *                          Set to NULL to use malloc() and free().
+ * \param       in          Beginning of the input buffer
+ * \param       in_size     Size of the input buffer
+ * \param       out         Beginning of the output buffer
+ * \param       out_pos     The next byte will be written to out[*out_pos].
+ *                          *out_pos is updated only if encoding succeeds.
+ * \param       out_size    Size of the out buffer; the first byte into
+ *                          which no data is written to is out[out_size].
+ *
+ * \return      - LZMA_OK: Encoding was successful.
+ *              - LZMA_BUF_ERROR: Not enough output buffer space.
+ *              - LZMA_UNSUPPORTED_CHECK
+ *              - LZMA_OPTIONS_ERROR
+ *              - LZMA_MEM_ERROR
+ *              - LZMA_DATA_ERROR
+ *              - LZMA_PROG_ERROR
+ */
+extern LZMA_API(lzma_ret) lzma_block_buffer_encode(
+		lzma_block *block, lzma_allocator *allocator,
+		const uint8_t *in, size_t in_size,
+		uint8_t *out, size_t *out_pos, size_t out_size)
+		lzma_nothrow lzma_attr_warn_unused_result;
+
+
+/**
+ * \brief       Single-call .xz Block decoder
+ *
+ * This is single-call equivalent of lzma_block_decoder(), and requires that
+ * the caller has already decoded Block Header and checked its memory usage.
+ *
+ * \param       block       Block options just like with lzma_block_decoder().
+ * \param       allocator   lzma_allocator for custom allocator functions.
+ *                          Set to NULL to use malloc() and free().
+ * \param       in          Beginning of the input buffer
+ * \param       in_pos      The next byte will be read from in[*in_pos].
+ *                          *in_pos is updated only if decoding succeeds.
+ * \param       in_size     Size of the input buffer; the first byte that
+ *                          won't be read is in[in_size].
+ * \param       out         Beginning of the output buffer
+ * \param       out_pos     The next byte will be written to out[*out_pos].
+ *                          *out_pos is updated only if encoding succeeds.
+ * \param       out_size    Size of the out buffer; the first byte into
+ *                          which no data is written to is out[out_size].
+ *
+ * \return      - LZMA_OK: Decoding was successful.
+ *              - LZMA_OPTIONS_ERROR
+ *              - LZMA_DATA_ERROR
+ *              - LZMA_MEM_ERROR
+ *              - LZMA_BUF_ERROR: Output buffer was too small.
+ *              - LZMA_PROG_ERROR
+ */
+extern LZMA_API(lzma_ret) lzma_block_buffer_decode(
+		lzma_block *block, lzma_allocator *allocator,
+		const uint8_t *in, size_t *in_pos, size_t in_size,
+		uint8_t *out, size_t *out_pos, size_t out_size)
+		lzma_nothrow;
diff --git a/Utilities/cmliblzma/liblzma/api/lzma/check.h b/Utilities/cmliblzma/liblzma/api/lzma/check.h
new file mode 100644
index 0000000..6a243db
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/api/lzma/check.h
@@ -0,0 +1,150 @@
+/**
+ * \file        lzma/check.h
+ * \brief       Integrity checks
+ */
+
+/*
+ * Author: Lasse Collin
+ *
+ * This file has been put into the public domain.
+ * You can do whatever you want with this file.
+ *
+ * See ../lzma.h for information about liblzma as a whole.
+ */
+
+#ifndef LZMA_H_INTERNAL
+#	error Never include this file directly. Use <lzma.h> instead.
+#endif
+
+
+/**
+ * \brief       Type of the integrity check (Check ID)
+ *
+ * The .xz format supports multiple types of checks that are calculated
+ * from the uncompressed data. They vary in both speed and ability to
+ * detect errors.
+ */
+typedef enum {
+	LZMA_CHECK_NONE     = 0,
+		/**<
+		 * No Check is calculated.
+		 *
+		 * Size of the Check field: 0 bytes
+		 */
+
+	LZMA_CHECK_CRC32    = 1,
+		/**<
+		 * CRC32 using the polynomial from the IEEE 802.3 standard
+		 *
+		 * Size of the Check field: 4 bytes
+		 */
+
+	LZMA_CHECK_CRC64    = 4,
+		/**<
+		 * CRC64 using the polynomial from the ECMA-182 standard
+		 *
+		 * Size of the Check field: 8 bytes
+		 */
+
+	LZMA_CHECK_SHA256   = 10
+		/**<
+		 * SHA-256
+		 *
+		 * Size of the Check field: 32 bytes
+		 */
+} lzma_check;
+
+
+/**
+ * \brief       Maximum valid Check ID
+ *
+ * The .xz file format specification specifies 16 Check IDs (0-15). Some
+ * of them are only reserved, that is, no actual Check algorithm has been
+ * assigned. When decoding, liblzma still accepts unknown Check IDs for
+ * future compatibility. If a valid but unsupported Check ID is detected,
+ * liblzma can indicate a warning; see the flags LZMA_TELL_NO_CHECK,
+ * LZMA_TELL_UNSUPPORTED_CHECK, and LZMA_TELL_ANY_CHECK in container.h.
+ */
+#define LZMA_CHECK_ID_MAX 15
+
+
+/**
+ * \brief       Test if the given Check ID is supported
+ *
+ * Return true if the given Check ID is supported by this liblzma build.
+ * Otherwise false is returned. It is safe to call this with a value that
+ * is not in the range [0, 15]; in that case the return value is always false.
+ *
+ * You can assume that LZMA_CHECK_NONE and LZMA_CHECK_CRC32 are always
+ * supported (even if liblzma is built with limited features).
+ */
+extern LZMA_API(lzma_bool) lzma_check_is_supported(lzma_check check)
+		lzma_nothrow lzma_attr_const;
+
+
+/**
+ * \brief       Get the size of the Check field with the given Check ID
+ *
+ * Although not all Check IDs have a check algorithm associated, the size of
+ * every Check is already frozen. This function returns the size (in bytes) of
+ * the Check field with the specified Check ID. The values are:
+ * { 0, 4, 4, 4, 8, 8, 8, 16, 16, 16, 32, 32, 32, 64, 64, 64 }
+ *
+ * If the argument is not in the range [0, 15], UINT32_MAX is returned.
+ */
+extern LZMA_API(uint32_t) lzma_check_size(lzma_check check)
+		lzma_nothrow lzma_attr_const;
+
+
+/**
+ * \brief       Maximum size of a Check field
+ */
+#define LZMA_CHECK_SIZE_MAX 64
+
+
+/**
+ * \brief       Calculate CRC32
+ *
+ * Calculate CRC32 using the polynomial from the IEEE 802.3 standard.
+ *
+ * \param       buf     Pointer to the input buffer
+ * \param       size    Size of the input buffer
+ * \param       crc     Previously returned CRC value. This is used to
+ *                      calculate the CRC of a big buffer in smaller chunks.
+ *                      Set to zero when starting a new calculation.
+ *
+ * \return      Updated CRC value, which can be passed to this function
+ *              again to continue CRC calculation.
+ */
+extern LZMA_API(uint32_t) lzma_crc32(
+		const uint8_t *buf, size_t size, uint32_t crc)
+		lzma_nothrow lzma_attr_pure;
+
+
+/**
+ * \brief       Calculate CRC64
+ *
+ * Calculate CRC64 using the polynomial from the ECMA-182 standard.
+ *
+ * This function is used similarly to lzma_crc32(). See its documentation.
+ */
+extern LZMA_API(uint64_t) lzma_crc64(
+		const uint8_t *buf, size_t size, uint64_t crc)
+		lzma_nothrow lzma_attr_pure;
+
+
+/*
+ * SHA-256 functions are currently not exported to public API.
+ * Contact Lasse Collin if you think it should be.
+ */
+
+
+/**
+ * \brief       Get the type of the integrity check
+ *
+ * This function can be called only immediately after lzma_code() has
+ * returned LZMA_NO_CHECK, LZMA_UNSUPPORTED_CHECK, or LZMA_GET_CHECK.
+ * Calling this function in any other situation has undefined behavior.
+ */
+extern LZMA_API(lzma_check) lzma_get_check(const lzma_stream *strm)
+		lzma_nothrow;
diff --git a/Utilities/cmliblzma/liblzma/api/lzma/container.h b/Utilities/cmliblzma/liblzma/api/lzma/container.h
new file mode 100644
index 0000000..7a9ffc6
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/api/lzma/container.h
@@ -0,0 +1,424 @@
+/**
+ * \file        lzma/container.h
+ * \brief       File formats
+ */
+
+/*
+ * Author: Lasse Collin
+ *
+ * This file has been put into the public domain.
+ * You can do whatever you want with this file.
+ *
+ * See ../lzma.h for information about liblzma as a whole.
+ */
+
+#ifndef LZMA_H_INTERNAL
+#	error Never include this file directly. Use <lzma.h> instead.
+#endif
+
+
+/************
+ * Encoding *
+ ************/
+
+/**
+ * \brief       Default compression preset
+ *
+ * It's not straightforward to recommend a default preset, because in some
+ * cases keeping the resource usage relatively low is more important that
+ * getting the maximum compression ratio.
+ */
+#define LZMA_PRESET_DEFAULT     UINT32_C(6)
+
+
+/**
+ * \brief       Mask for preset level
+ *
+ * This is useful only if you need to extract the level from the preset
+ * variable. That should be rare.
+ */
+#define LZMA_PRESET_LEVEL_MASK  UINT32_C(0x1F)
+
+
+/*
+ * Preset flags
+ *
+ * Currently only one flag is defined.
+ */
+
+/**
+ * \brief       Extreme compression preset
+ *
+ * This flag modifies the preset to make the encoding significantly slower
+ * while improving the compression ratio only marginally. This is useful
+ * when you don't mind wasting time to get as small result as possible.
+ *
+ * This flag doesn't affect the memory usage requirements of the decoder (at
+ * least not significantly). The memory usage of the encoder may be increased
+ * a little but only at the lowest preset levels (0-3).
+ */
+#define LZMA_PRESET_EXTREME       (UINT32_C(1) << 31)
+
+
+/**
+ * \brief       Calculate approximate memory usage of easy encoder
+ *
+ * This function is a wrapper for lzma_raw_encoder_memusage().
+ *
+ * \param       preset  Compression preset (level and possible flags)
+ *
+ * \return      Number of bytes of memory required for the given
+ *              preset when encoding. If an error occurs, for example
+ *              due to unsupported preset, UINT64_MAX is returned.
+ */
+extern LZMA_API(uint64_t) lzma_easy_encoder_memusage(uint32_t preset)
+		lzma_nothrow lzma_attr_pure;
+
+
+/**
+ * \brief       Calculate approximate decoder memory usage of a preset
+ *
+ * This function is a wrapper for lzma_raw_decoder_memusage().
+ *
+ * \param       preset  Compression preset (level and possible flags)
+ *
+ * \return      Number of bytes of memory required to decompress a file
+ *              that was compressed using the given preset. If an error
+ *              occurs, for example due to unsupported preset, UINT64_MAX
+ *              is returned.
+ */
+extern LZMA_API(uint64_t) lzma_easy_decoder_memusage(uint32_t preset)
+		lzma_nothrow lzma_attr_pure;
+
+
+/**
+ * \brief       Initialize .xz Stream encoder using a preset number
+ *
+ * This function is intended for those who just want to use the basic features
+ * if liblzma (that is, most developers out there).
+ *
+ * \param       strm    Pointer to lzma_stream that is at least initialized
+ *                      with LZMA_STREAM_INIT.
+ * \param       preset  Compression preset to use. A preset consist of level
+ *                      number and zero or more flags. Usually flags aren't
+ *                      used, so preset is simply a number [0, 9] which match
+ *                      the options -0 ... -9 of the xz command line tool.
+ *                      Additional flags can be be set using bitwise-or with
+ *                      the preset level number, e.g. 6 | LZMA_PRESET_EXTREME.
+ * \param       check   Integrity check type to use. See check.h for available
+ *                      checks. The xz command line tool defaults to
+ *                      LZMA_CHECK_CRC64, which is a good choice if you are
+ *                      unsure. LZMA_CHECK_CRC32 is good too as long as the
+ *                      uncompressed file is not many gigabytes.
+ *
+ * \return      - LZMA_OK: Initialization succeeded. Use lzma_code() to
+ *                encode your data.
+ *              - LZMA_MEM_ERROR: Memory allocation failed.
+ *              - LZMA_OPTIONS_ERROR: The given compression preset is not
+ *                supported by this build of liblzma.
+ *              - LZMA_UNSUPPORTED_CHECK: The given check type is not
+ *                supported by this liblzma build.
+ *              - LZMA_PROG_ERROR: One or more of the parameters have values
+ *                that will never be valid. For example, strm == NULL.
+ *
+ * If initialization fails (return value is not LZMA_OK), all the memory
+ * allocated for *strm by liblzma is always freed. Thus, there is no need
+ * to call lzma_end() after failed initialization.
+ *
+ * If initialization succeeds, use lzma_code() to do the actual encoding.
+ * Valid values for `action' (the second argument of lzma_code()) are
+ * LZMA_RUN, LZMA_SYNC_FLUSH, LZMA_FULL_FLUSH, and LZMA_FINISH. In future,
+ * there may be compression levels or flags that don't support LZMA_SYNC_FLUSH.
+ */
+extern LZMA_API(lzma_ret) lzma_easy_encoder(
+		lzma_stream *strm, uint32_t preset, lzma_check check)
+		lzma_nothrow lzma_attr_warn_unused_result;
+
+
+/**
+ * \brief       Single-call .xz Stream encoding using a preset number
+ *
+ * The maximum required output buffer size can be calculated with
+ * lzma_stream_buffer_bound().
+ *
+ * \param       preset      Compression preset to use. See the description
+ *                          in lzma_easy_encoder().
+ * \param       check       Type of the integrity check to calculate from
+ *                          uncompressed data.
+ * \param       allocator   lzma_allocator for custom allocator functions.
+ *                          Set to NULL to use malloc() and free().
+ * \param       in          Beginning of the input buffer
+ * \param       in_size     Size of the input buffer
+ * \param       out         Beginning of the output buffer
+ * \param       out_pos     The next byte will be written to out[*out_pos].
+ *                          *out_pos is updated only if encoding succeeds.
+ * \param       out_size    Size of the out buffer; the first byte into
+ *                          which no data is written to is out[out_size].
+ *
+ * \return      - LZMA_OK: Encoding was successful.
+ *              - LZMA_BUF_ERROR: Not enough output buffer space.
+ *              - LZMA_UNSUPPORTED_CHECK
+ *              - LZMA_OPTIONS_ERROR
+ *              - LZMA_MEM_ERROR
+ *              - LZMA_DATA_ERROR
+ *              - LZMA_PROG_ERROR
+ */
+extern LZMA_API(lzma_ret) lzma_easy_buffer_encode(
+		uint32_t preset, lzma_check check,
+		lzma_allocator *allocator, const uint8_t *in, size_t in_size,
+		uint8_t *out, size_t *out_pos, size_t out_size) lzma_nothrow;
+
+
+/**
+ * \brief       Initialize .xz Stream encoder using a custom filter chain
+ *
+ * \param       strm    Pointer to properly prepared lzma_stream
+ * \param       filters Array of filters. This must be terminated with
+ *                      filters[n].id = LZMA_VLI_UNKNOWN. See filter.h for
+ *                      more information.
+ * \param       check   Type of the integrity check to calculate from
+ *                      uncompressed data.
+ *
+ * \return      - LZMA_OK: Initialization was successful.
+ *              - LZMA_MEM_ERROR
+ *              - LZMA_UNSUPPORTED_CHECK
+ *              - LZMA_OPTIONS_ERROR
+ *              - LZMA_PROG_ERROR
+ */
+extern LZMA_API(lzma_ret) lzma_stream_encoder(lzma_stream *strm,
+		const lzma_filter *filters, lzma_check check)
+		lzma_nothrow lzma_attr_warn_unused_result;
+
+
+/**
+ * \brief       Initialize .lzma encoder (legacy file format)
+ *
+ * The .lzma format is sometimes called the LZMA_Alone format, which is the
+ * reason for the name of this function. The .lzma format supports only the
+ * LZMA1 filter. There is no support for integrity checks like CRC32.
+ *
+ * Use this function if and only if you need to create files readable by
+ * legacy LZMA tools such as LZMA Utils 4.32.x. Moving to the .xz format
+ * is strongly recommended.
+ *
+ * The valid action values for lzma_code() are LZMA_RUN and LZMA_FINISH.
+ * No kind of flushing is supported, because the file format doesn't make
+ * it possible.
+ *
+ * \return      - LZMA_OK
+ *              - LZMA_MEM_ERROR
+ *              - LZMA_OPTIONS_ERROR
+ *              - LZMA_PROG_ERROR
+ */
+extern LZMA_API(lzma_ret) lzma_alone_encoder(
+		lzma_stream *strm, const lzma_options_lzma *options)
+		lzma_nothrow lzma_attr_warn_unused_result;
+
+
+/**
+ * \brief       Calculate output buffer size for single-call Stream encoder
+ *
+ * When trying to compress uncompressible data, the encoded size will be
+ * slightly bigger than the input data. This function calculates how much
+ * output buffer space is required to be sure that lzma_stream_buffer_encode()
+ * doesn't return LZMA_BUF_ERROR.
+ *
+ * The calculated value is not exact, but it is guaranteed to be big enough.
+ * The actual maximum output space required may be slightly smaller (up to
+ * about 100 bytes). This should not be a problem in practice.
+ *
+ * If the calculated maximum size doesn't fit into size_t or would make the
+ * Stream grow past LZMA_VLI_MAX (which should never happen in practice),
+ * zero is returned to indicate the error.
+ *
+ * \note        The limit calculated by this function applies only to
+ *              single-call encoding. Multi-call encoding may (and probably
+ *              will) have larger maximum expansion when encoding
+ *              uncompressible data. Currently there is no function to
+ *              calculate the maximum expansion of multi-call encoding.
+ */
+extern LZMA_API(size_t) lzma_stream_buffer_bound(size_t uncompressed_size)
+		lzma_nothrow;
+
+
+/**
+ * \brief       Single-call .xz Stream encoder
+ *
+ * \param       filters     Array of filters. This must be terminated with
+ *                          filters[n].id = LZMA_VLI_UNKNOWN. See filter.h
+ *                          for more information.
+ * \param       check       Type of the integrity check to calculate from
+ *                          uncompressed data.
+ * \param       allocator   lzma_allocator for custom allocator functions.
+ *                          Set to NULL to use malloc() and free().
+ * \param       in          Beginning of the input buffer
+ * \param       in_size     Size of the input buffer
+ * \param       out         Beginning of the output buffer
+ * \param       out_pos     The next byte will be written to out[*out_pos].
+ *                          *out_pos is updated only if encoding succeeds.
+ * \param       out_size    Size of the out buffer; the first byte into
+ *                          which no data is written to is out[out_size].
+ *
+ * \return      - LZMA_OK: Encoding was successful.
+ *              - LZMA_BUF_ERROR: Not enough output buffer space.
+ *              - LZMA_UNSUPPORTED_CHECK
+ *              - LZMA_OPTIONS_ERROR
+ *              - LZMA_MEM_ERROR
+ *              - LZMA_DATA_ERROR
+ *              - LZMA_PROG_ERROR
+ */
+extern LZMA_API(lzma_ret) lzma_stream_buffer_encode(
+		lzma_filter *filters, lzma_check check,
+		lzma_allocator *allocator, const uint8_t *in, size_t in_size,
+		uint8_t *out, size_t *out_pos, size_t out_size)
+		lzma_nothrow lzma_attr_warn_unused_result;
+
+
+/************
+ * Decoding *
+ ************/
+
+/**
+ * This flag makes lzma_code() return LZMA_NO_CHECK if the input stream
+ * being decoded has no integrity check. Note that when used with
+ * lzma_auto_decoder(), all .lzma files will trigger LZMA_NO_CHECK
+ * if LZMA_TELL_NO_CHECK is used.
+ */
+#define LZMA_TELL_NO_CHECK              UINT32_C(0x01)
+
+
+/**
+ * This flag makes lzma_code() return LZMA_UNSUPPORTED_CHECK if the input
+ * stream has an integrity check, but the type of the integrity check is not
+ * supported by this liblzma version or build. Such files can still be
+ * decoded, but the integrity check cannot be verified.
+ */
+#define LZMA_TELL_UNSUPPORTED_CHECK     UINT32_C(0x02)
+
+
+/**
+ * This flag makes lzma_code() return LZMA_GET_CHECK as soon as the type
+ * of the integrity check is known. The type can then be got with
+ * lzma_get_check().
+ */
+#define LZMA_TELL_ANY_CHECK             UINT32_C(0x04)
+
+
+/**
+ * This flag enables decoding of concatenated files with file formats that
+ * allow concatenating compressed files as is. From the formats currently
+ * supported by liblzma, only the .xz format allows concatenated files.
+ * Concatenated files are not allowed with the legacy .lzma format.
+ *
+ * This flag also affects the usage of the `action' argument for lzma_code().
+ * When LZMA_CONCATENATED is used, lzma_code() won't return LZMA_STREAM_END
+ * unless LZMA_FINISH is used as `action'. Thus, the application has to set
+ * LZMA_FINISH in the same way as it does when encoding.
+ *
+ * If LZMA_CONCATENATED is not used, the decoders still accept LZMA_FINISH
+ * as `action' for lzma_code(), but the usage of LZMA_FINISH isn't required.
+ */
+#define LZMA_CONCATENATED               UINT32_C(0x08)
+
+
+/**
+ * \brief       Initialize .xz Stream decoder
+ *
+ * \param       strm        Pointer to properly prepared lzma_stream
+ * \param       memlimit    Memory usage limit as bytes. Use UINT64_MAX
+ *                          to effectively disable the limiter.
+ * \param       flags       Bitwise-or of zero or more of the decoder flags:
+ *                          LZMA_TELL_NO_CHECK, LZMA_TELL_UNSUPPORTED_CHECK,
+ *                          LZMA_TELL_ANY_CHECK, LZMA_CONCATENATED
+ *
+ * \return      - LZMA_OK: Initialization was successful.
+ *              - LZMA_MEM_ERROR: Cannot allocate memory.
+ *              - LZMA_OPTIONS_ERROR: Unsupported flags
+ *              - LZMA_PROG_ERROR
+ */
+extern LZMA_API(lzma_ret) lzma_stream_decoder(
+		lzma_stream *strm, uint64_t memlimit, uint32_t flags)
+		lzma_nothrow lzma_attr_warn_unused_result;
+
+
+/**
+ * \brief       Decode .xz Streams and .lzma files with autodetection
+ *
+ * This decoder autodetects between the .xz and .lzma file formats, and
+ * calls lzma_stream_decoder() or lzma_alone_decoder() once the type
+ * of the input file has been detected.
+ *
+ * \param       strm        Pointer to properly prepared lzma_stream
+ * \param       memlimit    Memory usage limit as bytes. Use UINT64_MAX
+ *                          to effectively disable the limiter.
+ * \param       flags       Bitwise-or of flags, or zero for no flags.
+ *
+ * \return      - LZMA_OK: Initialization was successful.
+ *              - LZMA_MEM_ERROR: Cannot allocate memory.
+ *              - LZMA_OPTIONS_ERROR: Unsupported flags
+ *              - LZMA_PROG_ERROR
+ */
+extern LZMA_API(lzma_ret) lzma_auto_decoder(
+		lzma_stream *strm, uint64_t memlimit, uint32_t flags)
+		lzma_nothrow lzma_attr_warn_unused_result;
+
+
+/**
+ * \brief       Initialize .lzma decoder (legacy file format)
+ *
+ * Valid `action' arguments to lzma_code() are LZMA_RUN and LZMA_FINISH.
+ * There is no need to use LZMA_FINISH, but allowing it may simplify
+ * certain types of applications.
+ *
+ * \return      - LZMA_OK
+ *              - LZMA_MEM_ERROR
+ *              - LZMA_PROG_ERROR
+ */
+extern LZMA_API(lzma_ret) lzma_alone_decoder(
+		lzma_stream *strm, uint64_t memlimit)
+		lzma_nothrow lzma_attr_warn_unused_result;
+
+
+/**
+ * \brief       Single-call .xz Stream decoder
+ *
+ * \param       memlimit    Pointer to how much memory the decoder is allowed
+ *                          to allocate. The value pointed by this pointer is
+ *                          modified if and only if LZMA_MEMLIMIT_ERROR is
+ *                          returned.
+ * \param       flags       Bitwise-or of zero or more of the decoder flags:
+ *                          LZMA_TELL_NO_CHECK, LZMA_TELL_UNSUPPORTED_CHECK,
+ *                          LZMA_CONCATENATED. Note that LZMA_TELL_ANY_CHECK
+ *                          is not allowed and will return LZMA_PROG_ERROR.
+ * \param       allocator   lzma_allocator for custom allocator functions.
+ *                          Set to NULL to use malloc() and free().
+ * \param       in          Beginning of the input buffer
+ * \param       in_pos      The next byte will be read from in[*in_pos].
+ *                          *in_pos is updated only if decoding succeeds.
+ * \param       in_size     Size of the input buffer; the first byte that
+ *                          won't be read is in[in_size].
+ * \param       out         Beginning of the output buffer
+ * \param       out_pos     The next byte will be written to out[*out_pos].
+ *                          *out_pos is updated only if decoding succeeds.
+ * \param       out_size    Size of the out buffer; the first byte into
+ *                          which no data is written to is out[out_size].
+ *
+ * \return      - LZMA_OK: Decoding was successful.
+ *              - LZMA_FORMAT_ERROR
+ *              - LZMA_OPTIONS_ERROR
+ *              - LZMA_DATA_ERROR
+ *              - LZMA_NO_CHECK: This can be returned only if using
+ *                the LZMA_TELL_NO_CHECK flag.
+ *              - LZMA_UNSUPPORTED_CHECK: This can be returned only if using
+ *                the LZMA_TELL_UNSUPPORTED_CHECK flag.
+ *              - LZMA_MEM_ERROR
+ *              - LZMA_MEMLIMIT_ERROR: Memory usage limit was reached.
+ *                The minimum required memlimit value was stored to *memlimit.
+ *              - LZMA_BUF_ERROR: Output buffer was too small.
+ *              - LZMA_PROG_ERROR
+ */
+extern LZMA_API(lzma_ret) lzma_stream_buffer_decode(
+		uint64_t *memlimit, uint32_t flags, lzma_allocator *allocator,
+		const uint8_t *in, size_t *in_pos, size_t in_size,
+		uint8_t *out, size_t *out_pos, size_t out_size)
+		lzma_nothrow lzma_attr_warn_unused_result;
diff --git a/Utilities/cmliblzma/liblzma/api/lzma/delta.h b/Utilities/cmliblzma/liblzma/api/lzma/delta.h
new file mode 100644
index 0000000..592fc4f
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/api/lzma/delta.h
@@ -0,0 +1,77 @@
+/**
+ * \file        lzma/delta.h
+ * \brief       Delta filter
+ */
+
+/*
+ * Author: Lasse Collin
+ *
+ * This file has been put into the public domain.
+ * You can do whatever you want with this file.
+ *
+ * See ../lzma.h for information about liblzma as a whole.
+ */
+
+#ifndef LZMA_H_INTERNAL
+#	error Never include this file directly. Use <lzma.h> instead.
+#endif
+
+
+/**
+ * \brief       Filter ID
+ *
+ * Filter ID of the Delta filter. This is used as lzma_filter.id.
+ */
+#define LZMA_FILTER_DELTA       LZMA_VLI_C(0x03)
+
+
+/**
+ * \brief       Type of the delta calculation
+ *
+ * Currently only byte-wise delta is supported. Other possible types could
+ * be, for example, delta of 16/32/64-bit little/big endian integers, but
+ * these are not currently planned since byte-wise delta is almost as good.
+ */
+typedef enum {
+	LZMA_DELTA_TYPE_BYTE
+} lzma_delta_type;
+
+
+/**
+ * \brief       Options for the Delta filter
+ *
+ * These options are needed by both encoder and decoder.
+ */
+typedef struct {
+	/** For now, this must always be LZMA_DELTA_TYPE_BYTE. */
+	lzma_delta_type type;
+
+	/**
+	 * \brief       Delta distance
+	 *
+	 * With the only currently supported type, LZMA_DELTA_TYPE_BYTE,
+	 * the distance is as bytes.
+	 *
+	 * Examples:
+	 *  - 16-bit stereo audio: distance = 4 bytes
+	 *  - 24-bit RGB image data: distance = 3 bytes
+	 */
+	uint32_t dist;
+#	define LZMA_DELTA_DIST_MIN 1
+#	define LZMA_DELTA_DIST_MAX 256
+
+	/*
+	 * Reserved space to allow possible future extensions without
+	 * breaking the ABI. You should not touch these, because the names
+	 * of these variables may change. These are and will never be used
+	 * when type is LZMA_DELTA_TYPE_BYTE, so it is safe to leave these
+	 * uninitialized.
+	 */
+	uint32_t reserved_int1;
+	uint32_t reserved_int2;
+	uint32_t reserved_int3;
+	uint32_t reserved_int4;
+	void *reserved_ptr1;
+	void *reserved_ptr2;
+
+} lzma_options_delta;
diff --git a/Utilities/cmliblzma/liblzma/api/lzma/filter.h b/Utilities/cmliblzma/liblzma/api/lzma/filter.h
new file mode 100644
index 0000000..e0bc163
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/api/lzma/filter.h
@@ -0,0 +1,424 @@
+/**
+ * \file        lzma/filter.h
+ * \brief       Common filter related types and functions
+ */
+
+/*
+ * Author: Lasse Collin
+ *
+ * This file has been put into the public domain.
+ * You can do whatever you want with this file.
+ *
+ * See ../lzma.h for information about liblzma as a whole.
+ */
+
+#ifndef LZMA_H_INTERNAL
+#	error Never include this file directly. Use <lzma.h> instead.
+#endif
+
+
+/**
+ * \brief       Maximum number of filters in a chain
+ *
+ * A filter chain can have 1-4 filters, of which three are allowed to change
+ * the size of the data. Usually only one or two filters are needed.
+ */
+#define LZMA_FILTERS_MAX 4
+
+
+/**
+ * \brief       Filter options
+ *
+ * This structure is used to pass Filter ID and a pointer filter's
+ * options to liblzma. A few functions work with a single lzma_filter
+ * structure, while most functions expect a filter chain.
+ *
+ * A filter chain is indicated with an array of lzma_filter structures.
+ * The array is terminated with .id = LZMA_VLI_UNKNOWN. Thus, the filter
+ * array must have LZMA_FILTERS_MAX + 1 elements (that is, five) to
+ * be able to hold any arbitrary filter chain. This is important when
+ * using lzma_block_header_decode() from block.h, because too small
+ * array would make liblzma write past the end of the filters array.
+ */
+typedef struct {
+	/**
+	 * \brief       Filter ID
+	 *
+	 * Use constants whose name begin with `LZMA_FILTER_' to specify
+	 * different filters. In an array of lzma_filter structures, use
+	 * LZMA_VLI_UNKNOWN to indicate end of filters.
+	 *
+	 * \note        This is not an enum, because on some systems enums
+	 *              cannot be 64-bit.
+	 */
+	lzma_vli id;
+
+	/**
+	 * \brief       Pointer to filter-specific options structure
+	 *
+	 * If the filter doesn't need options, set this to NULL. If id is
+	 * set to LZMA_VLI_UNKNOWN, options is ignored, and thus
+	 * doesn't need be initialized.
+	 */
+	void *options;
+
+} lzma_filter;
+
+
+/**
+ * \brief       Test if the given Filter ID is supported for encoding
+ *
+ * Return true if the give Filter ID is supported for encoding by this
+ * liblzma build. Otherwise false is returned.
+ *
+ * There is no way to list which filters are available in this particular
+ * liblzma version and build. It would be useless, because the application
+ * couldn't know what kind of options the filter would need.
+ */
+extern LZMA_API(lzma_bool) lzma_filter_encoder_is_supported(lzma_vli id)
+		lzma_nothrow lzma_attr_const;
+
+
+/**
+ * \brief       Test if the given Filter ID is supported for decoding
+ *
+ * Return true if the give Filter ID is supported for decoding by this
+ * liblzma build. Otherwise false is returned.
+ */
+extern LZMA_API(lzma_bool) lzma_filter_decoder_is_supported(lzma_vli id)
+		lzma_nothrow lzma_attr_const;
+
+
+/**
+ * \brief       Copy the filters array
+ *
+ * Copy the Filter IDs and filter-specific options from src to dest.
+ * Up to LZMA_FILTERS_MAX filters are copied, plus the terminating
+ * .id == LZMA_VLI_UNKNOWN. Thus, dest should have at least
+ * LZMA_FILTERS_MAX + 1 elements space unless the caller knows that
+ * src is smaller than that.
+ *
+ * Unless the filter-specific options is NULL, the Filter ID has to be
+ * supported by liblzma, because liblzma needs to know the size of every
+ * filter-specific options structure. The filter-specific options are not
+ * validated. If options is NULL, any unsupported Filter IDs are copied
+ * without returning an error.
+ *
+ * Old filter-specific options in dest are not freed, so dest doesn't
+ * need to be initialized by the caller in any way.
+ *
+ * If an error occurs, memory possibly already allocated by this function
+ * is always freed.
+ *
+ * \return      - LZMA_OK
+ *              - LZMA_MEM_ERROR
+ *              - LZMA_OPTIONS_ERROR: Unsupported Filter ID and its options
+ *                is not NULL.
+ *              - LZMA_PROG_ERROR: src or dest is NULL.
+ */
+extern LZMA_API(lzma_ret) lzma_filters_copy(const lzma_filter *src,
+		lzma_filter *dest, lzma_allocator *allocator) lzma_nothrow;
+
+
+/**
+ * \brief       Calculate approximate memory requirements for raw encoder
+ *
+ * This function can be used to calculate the memory requirements for
+ * Block and Stream encoders too because Block and Stream encoders don't
+ * need significantly more memory than raw encoder.
+ *
+ * \param       filters     Array of filters terminated with
+ *                          .id == LZMA_VLI_UNKNOWN.
+ *
+ * \return      Number of bytes of memory required for the given
+ *              filter chain when encoding. If an error occurs,
+ *              for example due to unsupported filter chain,
+ *              UINT64_MAX is returned.
+ */
+extern LZMA_API(uint64_t) lzma_raw_encoder_memusage(const lzma_filter *filters)
+		lzma_nothrow lzma_attr_pure;
+
+
+/**
+ * \brief       Calculate approximate memory requirements for raw decoder
+ *
+ * This function can be used to calculate the memory requirements for
+ * Block and Stream decoders too because Block and Stream decoders don't
+ * need significantly more memory than raw decoder.
+ *
+ * \param       filters     Array of filters terminated with
+ *                          .id == LZMA_VLI_UNKNOWN.
+ *
+ * \return      Number of bytes of memory required for the given
+ *              filter chain when decoding. If an error occurs,
+ *              for example due to unsupported filter chain,
+ *              UINT64_MAX is returned.
+ */
+extern LZMA_API(uint64_t) lzma_raw_decoder_memusage(const lzma_filter *filters)
+		lzma_nothrow lzma_attr_pure;
+
+
+/**
+ * \brief       Initialize raw encoder
+ *
+ * This function may be useful when implementing custom file formats.
+ *
+ * \param       strm    Pointer to properly prepared lzma_stream
+ * \param       filters Array of lzma_filter structures. The end of the
+ *                      array must be marked with .id = LZMA_VLI_UNKNOWN.
+ *
+ * The `action' with lzma_code() can be LZMA_RUN, LZMA_SYNC_FLUSH (if the
+ * filter chain supports it), or LZMA_FINISH.
+ *
+ * \return      - LZMA_OK
+ *              - LZMA_MEM_ERROR
+ *              - LZMA_OPTIONS_ERROR
+ *              - LZMA_PROG_ERROR
+ */
+extern LZMA_API(lzma_ret) lzma_raw_encoder(
+		lzma_stream *strm, const lzma_filter *filters)
+		lzma_nothrow lzma_attr_warn_unused_result;
+
+
+/**
+ * \brief       Initialize raw decoder
+ *
+ * The initialization of raw decoder goes similarly to raw encoder.
+ *
+ * The `action' with lzma_code() can be LZMA_RUN or LZMA_FINISH. Using
+ * LZMA_FINISH is not required, it is supported just for convenience.
+ *
+ * \return      - LZMA_OK
+ *              - LZMA_MEM_ERROR
+ *              - LZMA_OPTIONS_ERROR
+ *              - LZMA_PROG_ERROR
+ */
+extern LZMA_API(lzma_ret) lzma_raw_decoder(
+		lzma_stream *strm, const lzma_filter *filters)
+		lzma_nothrow lzma_attr_warn_unused_result;
+
+
+/**
+ * \brief       Update the filter chain in the encoder
+ *
+ * This function is for advanced users only. This function has two slightly
+ * different purposes:
+ *
+ *  - After LZMA_FULL_FLUSH when using Stream encoder: Set a new filter
+ *    chain, which will be used starting from the next Block.
+ *
+ *  - After LZMA_SYNC_FLUSH using Raw, Block, or Stream encoder: Change
+ *    the filter-specific options in the middle of encoding. The actual
+ *    filters in the chain (Filter IDs) cannot be changed. In the future,
+ *    it might become possible to change the filter options without
+ *    using LZMA_SYNC_FLUSH.
+ *
+ * While rarely useful, this function may be called also when no data has
+ * been compressed yet. In that case, this function will behave as if
+ * LZMA_FULL_FLUSH (Stream encoder) or LZMA_SYNC_FLUSH (Raw or Block
+ * encoder) had been used right before calling this function.
+ *
+ * \return      - LZMA_OK
+ *              - LZMA_MEM_ERROR
+ *              - LZMA_MEMLIMIT_ERROR
+ *              - LZMA_OPTIONS_ERROR
+ *              - LZMA_PROG_ERROR
+ */
+extern LZMA_API(lzma_ret) lzma_filters_update(
+		lzma_stream *strm, const lzma_filter *filters) lzma_nothrow;
+
+
+/**
+ * \brief       Single-call raw encoder
+ *
+ * \param       filters     Array of lzma_filter structures. The end of the
+ *                          array must be marked with .id = LZMA_VLI_UNKNOWN.
+ * \param       allocator   lzma_allocator for custom allocator functions.
+ *                          Set to NULL to use malloc() and free().
+ * \param       in          Beginning of the input buffer
+ * \param       in_size     Size of the input buffer
+ * \param       out         Beginning of the output buffer
+ * \param       out_pos     The next byte will be written to out[*out_pos].
+ *                          *out_pos is updated only if encoding succeeds.
+ * \param       out_size    Size of the out buffer; the first byte into
+ *                          which no data is written to is out[out_size].
+ *
+ * \return      - LZMA_OK: Encoding was successful.
+ *              - LZMA_BUF_ERROR: Not enough output buffer space.
+ *              - LZMA_OPTIONS_ERROR
+ *              - LZMA_MEM_ERROR
+ *              - LZMA_DATA_ERROR
+ *              - LZMA_PROG_ERROR
+ *
+ * \note        There is no function to calculate how big output buffer
+ *              would surely be big enough. (lzma_stream_buffer_bound()
+ *              works only for lzma_stream_buffer_encode(); raw encoder
+ *              won't necessarily meet that bound.)
+ */
+extern LZMA_API(lzma_ret) lzma_raw_buffer_encode(
+		const lzma_filter *filters, lzma_allocator *allocator,
+		const uint8_t *in, size_t in_size, uint8_t *out,
+		size_t *out_pos, size_t out_size) lzma_nothrow;
+
+
+/**
+ * \brief       Single-call raw decoder
+ *
+ * \param       filters     Array of lzma_filter structures. The end of the
+ *                          array must be marked with .id = LZMA_VLI_UNKNOWN.
+ * \param       allocator   lzma_allocator for custom allocator functions.
+ *                          Set to NULL to use malloc() and free().
+ * \param       in          Beginning of the input buffer
+ * \param       in_pos      The next byte will be read from in[*in_pos].
+ *                          *in_pos is updated only if decoding succeeds.
+ * \param       in_size     Size of the input buffer; the first byte that
+ *                          won't be read is in[in_size].
+ * \param       out         Beginning of the output buffer
+ * \param       out_pos     The next byte will be written to out[*out_pos].
+ *                          *out_pos is updated only if encoding succeeds.
+ * \param       out_size    Size of the out buffer; the first byte into
+ *                          which no data is written to is out[out_size].
+ */
+extern LZMA_API(lzma_ret) lzma_raw_buffer_decode(
+		const lzma_filter *filters, lzma_allocator *allocator,
+		const uint8_t *in, size_t *in_pos, size_t in_size,
+		uint8_t *out, size_t *out_pos, size_t out_size) lzma_nothrow;
+
+
+/**
+ * \brief       Get the size of the Filter Properties field
+ *
+ * This function may be useful when implementing custom file formats
+ * using the raw encoder and decoder.
+ *
+ * \param       size    Pointer to uint32_t to hold the size of the properties
+ * \param       filter  Filter ID and options (the size of the properties may
+ *                      vary depending on the options)
+ *
+ * \return      - LZMA_OK
+ *              - LZMA_OPTIONS_ERROR
+ *              - LZMA_PROG_ERROR
+ *
+ * \note        This function validates the Filter ID, but does not
+ *              necessarily validate the options. Thus, it is possible
+ *              that this returns LZMA_OK while the following call to
+ *              lzma_properties_encode() returns LZMA_OPTIONS_ERROR.
+ */
+extern LZMA_API(lzma_ret) lzma_properties_size(
+		uint32_t *size, const lzma_filter *filter) lzma_nothrow;
+
+
+/**
+ * \brief       Encode the Filter Properties field
+ *
+ * \param       filter  Filter ID and options
+ * \param       props   Buffer to hold the encoded options. The size of
+ *                      buffer must have been already determined with
+ *                      lzma_properties_size().
+ *
+ * \return      - LZMA_OK
+ *              - LZMA_OPTIONS_ERROR
+ *              - LZMA_PROG_ERROR
+ *
+ * \note        Even this function won't validate more options than actually
+ *              necessary. Thus, it is possible that encoding the properties
+ *              succeeds but using the same options to initialize the encoder
+ *              will fail.
+ *
+ * \note        If lzma_properties_size() indicated that the size
+ *              of the Filter Properties field is zero, calling
+ *              lzma_properties_encode() is not required, but it
+ *              won't do any harm either.
+ */
+extern LZMA_API(lzma_ret) lzma_properties_encode(
+		const lzma_filter *filter, uint8_t *props) lzma_nothrow;
+
+
+/**
+ * \brief       Decode the Filter Properties field
+ *
+ * \param       filter      filter->id must have been set to the correct
+ *                          Filter ID. filter->options doesn't need to be
+ *                          initialized (it's not freed by this function). The
+ *                          decoded options will be stored to filter->options.
+ *                          filter->options is set to NULL if there are no
+ *                          properties or if an error occurs.
+ * \param       allocator   Custom memory allocator used to allocate the
+ *                          options. Set to NULL to use the default malloc(),
+ *                          and in case of an error, also free().
+ * \param       props       Input buffer containing the properties.
+ * \param       props_size  Size of the properties. This must be the exact
+ *                          size; giving too much or too little input will
+ *                          return LZMA_OPTIONS_ERROR.
+ *
+ * \return      - LZMA_OK
+ *              - LZMA_OPTIONS_ERROR
+ *              - LZMA_MEM_ERROR
+ */
+extern LZMA_API(lzma_ret) lzma_properties_decode(
+		lzma_filter *filter, lzma_allocator *allocator,
+		const uint8_t *props, size_t props_size) lzma_nothrow;
+
+
+/**
+ * \brief       Calculate encoded size of a Filter Flags field
+ *
+ * Knowing the size of Filter Flags is useful to know when allocating
+ * memory to hold the encoded Filter Flags.
+ *
+ * \param       size    Pointer to integer to hold the calculated size
+ * \param       filter  Filter ID and associated options whose encoded
+ *                      size is to be calculated
+ *
+ * \return      - LZMA_OK: *size set successfully. Note that this doesn't
+ *                guarantee that filter->options is valid, thus
+ *                lzma_filter_flags_encode() may still fail.
+ *              - LZMA_OPTIONS_ERROR: Unknown Filter ID or unsupported options.
+ *              - LZMA_PROG_ERROR: Invalid options
+ *
+ * \note        If you need to calculate size of List of Filter Flags,
+ *              you need to loop over every lzma_filter entry.
+ */
+extern LZMA_API(lzma_ret) lzma_filter_flags_size(
+		uint32_t *size, const lzma_filter *filter)
+		lzma_nothrow lzma_attr_warn_unused_result;
+
+
+/**
+ * \brief       Encode Filter Flags into given buffer
+ *
+ * In contrast to some functions, this doesn't allocate the needed buffer.
+ * This is due to how this function is used internally by liblzma.
+ *
+ * \param       filter      Filter ID and options to be encoded
+ * \param       out         Beginning of the output buffer
+ * \param       out_pos     out[*out_pos] is the next write position. This
+ *                          is updated by the encoder.
+ * \param       out_size    out[out_size] is the first byte to not write.
+ *
+ * \return      - LZMA_OK: Encoding was successful.
+ *              - LZMA_OPTIONS_ERROR: Invalid or unsupported options.
+ *              - LZMA_PROG_ERROR: Invalid options or not enough output
+ *                buffer space (you should have checked it with
+ *                lzma_filter_flags_size()).
+ */
+extern LZMA_API(lzma_ret) lzma_filter_flags_encode(const lzma_filter *filter,
+		uint8_t *out, size_t *out_pos, size_t out_size)
+		lzma_nothrow lzma_attr_warn_unused_result;
+
+
+/**
+ * \brief       Decode Filter Flags from given buffer
+ *
+ * The decoded result is stored into *filter. The old value of
+ * filter->options is not free()d.
+ *
+ * \return      - LZMA_OK
+ *              - LZMA_OPTIONS_ERROR
+ *              - LZMA_MEM_ERROR
+ *              - LZMA_PROG_ERROR
+ */
+extern LZMA_API(lzma_ret) lzma_filter_flags_decode(
+		lzma_filter *filter, lzma_allocator *allocator,
+		const uint8_t *in, size_t *in_pos, size_t in_size)
+		lzma_nothrow lzma_attr_warn_unused_result;
diff --git a/Utilities/cmliblzma/liblzma/api/lzma/hardware.h b/Utilities/cmliblzma/liblzma/api/lzma/hardware.h
new file mode 100644
index 0000000..e7dd03c
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/api/lzma/hardware.h
@@ -0,0 +1,50 @@
+/**
+ * \file        lzma/hardware.h
+ * \brief       Hardware information
+ *
+ * Since liblzma can consume a lot of system resources, it also provides
+ * ways to limit the resource usage. Applications linking against liblzma
+ * need to do the actual decisions how much resources to let liblzma to use.
+ * To ease making these decisions, liblzma provides functions to find out
+ * the relevant capabilities of the underlaying hardware. Currently there
+ * is only a function to find out the amount of RAM, but in the future there
+ * will be also a function to detect how many concurrent threads the system
+ * can run.
+ *
+ * \note        On some operating systems, these function may temporarily
+ *              load a shared library or open file descriptor(s) to find out
+ *              the requested hardware information. Unless the application
+ *              assumes that specific file descriptors are not touched by
+ *              other threads, this should have no effect on thread safety.
+ *              Possible operations involving file descriptors will restart
+ *              the syscalls if they return EINTR.
+ */
+
+/*
+ * Author: Lasse Collin
+ *
+ * This file has been put into the public domain.
+ * You can do whatever you want with this file.
+ *
+ * See ../lzma.h for information about liblzma as a whole.
+ */
+
+#ifndef LZMA_H_INTERNAL
+#	error Never include this file directly. Use <lzma.h> instead.
+#endif
+
+
+/**
+ * \brief       Get the total amount of physical memory (RAM) in bytes
+ *
+ * This function may be useful when determining a reasonable memory
+ * usage limit for decompressing or how much memory it is OK to use
+ * for compressing.
+ *
+ * \return      On success, the total amount of physical memory in bytes
+ *              is returned. If the amount of RAM cannot be determined,
+ *              zero is returned. This can happen if an error occurs
+ *              or if there is no code in liblzma to detect the amount
+ *              of RAM on the specific operating system.
+ */
+extern LZMA_API(uint64_t) lzma_physmem(void) lzma_nothrow;
diff --git a/Utilities/cmliblzma/liblzma/api/lzma/index.h b/Utilities/cmliblzma/liblzma/api/lzma/index.h
new file mode 100644
index 0000000..16bacc2
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/api/lzma/index.h
@@ -0,0 +1,682 @@
+/**
+ * \file        lzma/index.h
+ * \brief       Handling of .xz Index and related information
+ */
+
+/*
+ * Author: Lasse Collin
+ *
+ * This file has been put into the public domain.
+ * You can do whatever you want with this file.
+ *
+ * See ../lzma.h for information about liblzma as a whole.
+ */
+
+#ifndef LZMA_H_INTERNAL
+#	error Never include this file directly. Use <lzma.h> instead.
+#endif
+
+
+/**
+ * \brief       Opaque data type to hold the Index(es) and other information
+ *
+ * lzma_index often holds just one .xz Index and possibly the Stream Flags
+ * of the same Stream and size of the Stream Padding field. However,
+ * multiple lzma_indexes can be concatenated with lzma_index_cat() and then
+ * there may be information about multiple Streams in the same lzma_index.
+ *
+ * Notes about thread safety: Only one thread may modify lzma_index at
+ * a time. All functions that take non-const pointer to lzma_index
+ * modify it. As long as no thread is modifying the lzma_index, getting
+ * information from the same lzma_index can be done from multiple threads
+ * at the same time with functions that take a const pointer to
+ * lzma_index or use lzma_index_iter. The same iterator must be used
+ * only by one thread at a time, of course, but there can be as many
+ * iterators for the same lzma_index as needed.
+ */
+typedef struct lzma_index_s lzma_index;
+
+
+/**
+ * \brief       Iterator to get information about Blocks and Streams
+ */
+typedef struct {
+	struct {
+		/**
+		 * \brief       Pointer to Stream Flags
+		 *
+		 * This is NULL if Stream Flags have not been set for
+		 * this Stream with lzma_index_stream_flags().
+		 */
+		const lzma_stream_flags *flags;
+
+		const void *reserved_ptr1;
+		const void *reserved_ptr2;
+		const void *reserved_ptr3;
+
+		/**
+		 * \brief       Stream number in the lzma_index
+		 *
+		 * The first Stream is 1.
+		 */
+		lzma_vli number;
+
+		/**
+		 * \brief       Number of Blocks in the Stream
+		 *
+		 * If this is zero, the block structure below has
+		 * undefined values.
+		 */
+		lzma_vli block_count;
+
+		/**
+		 * \brief       Compressed start offset of this Stream
+		 *
+		 * The offset is relative to the beginning of the lzma_index
+		 * (i.e. usually the beginning of the .xz file).
+		 */
+		lzma_vli compressed_offset;
+
+		/**
+		 * \brief       Uncompressed start offset of this Stream
+		 *
+		 * The offset is relative to the beginning of the lzma_index
+		 * (i.e. usually the beginning of the .xz file).
+		 */
+		lzma_vli uncompressed_offset;
+
+		/**
+		 * \brief       Compressed size of this Stream
+		 *
+		 * This includes all headers except the possible
+		 * Stream Padding after this Stream.
+		 */
+		lzma_vli compressed_size;
+
+		/**
+		 * \brief       Uncompressed size of this Stream
+		 */
+		lzma_vli uncompressed_size;
+
+		/**
+		 * \brief       Size of Stream Padding after this Stream
+		 *
+		 * If it hasn't been set with lzma_index_stream_padding(),
+		 * this defaults to zero. Stream Padding is always
+		 * a multiple of four bytes.
+		 */
+		lzma_vli padding;
+
+		lzma_vli reserved_vli1;
+		lzma_vli reserved_vli2;
+		lzma_vli reserved_vli3;
+		lzma_vli reserved_vli4;
+	} stream;
+
+	struct {
+		/**
+		 * \brief       Block number in the file
+		 *
+		 * The first Block is 1.
+		 */
+		lzma_vli number_in_file;
+
+		/**
+		 * \brief       Compressed start offset of this Block
+		 *
+		 * This offset is relative to the beginning of the
+		 * lzma_index (i.e. usually the beginning of the .xz file).
+		 * Normally this is where you should seek in the .xz file
+		 * to start decompressing this Block.
+		 */
+		lzma_vli compressed_file_offset;
+
+		/**
+		 * \brief       Uncompressed start offset of this Block
+		 *
+		 * This offset is relative to the beginning of the lzma_index
+		 * (i.e. usually the beginning of the .xz file).
+		 *
+		 * When doing random-access reading, it is possible that
+		 * the target offset is not exactly at Block boundary. One
+		 * will need to compare the target offset against
+		 * uncompressed_file_offset or uncompressed_stream_offset,
+		 * and possibly decode and throw away some amount of data
+		 * before reaching the target offset.
+		 */
+		lzma_vli uncompressed_file_offset;
+
+		/**
+		 * \brief       Block number in this Stream
+		 *
+		 * The first Block is 1.
+		 */
+		lzma_vli number_in_stream;
+
+		/**
+		 * \brief       Compressed start offset of this Block
+		 *
+		 * This offset is relative to the beginning of the Stream
+		 * containing this Block.
+		 */
+		lzma_vli compressed_stream_offset;
+
+		/**
+		 * \brief       Uncompressed start offset of this Block
+		 *
+		 * This offset is relative to the beginning of the Stream
+		 * containing this Block.
+		 */
+		lzma_vli uncompressed_stream_offset;
+
+		/**
+		 * \brief       Uncompressed size of this Block
+		 *
+		 * You should pass this to the Block decoder if you will
+		 * decode this Block. It will allow the Block decoder to
+		 * validate the uncompressed size.
+		 */
+		lzma_vli uncompressed_size;
+
+		/**
+		 * \brief       Unpadded size of this Block
+		 *
+		 * You should pass this to the Block decoder if you will
+		 * decode this Block. It will allow the Block decoder to
+		 * validate the unpadded size.
+		 */
+		lzma_vli unpadded_size;
+
+		/**
+		 * \brief       Total compressed size
+		 *
+		 * This includes all headers and padding in this Block.
+		 * This is useful if you need to know how many bytes
+		 * the Block decoder will actually read.
+		 */
+		lzma_vli total_size;
+
+		lzma_vli reserved_vli1;
+		lzma_vli reserved_vli2;
+		lzma_vli reserved_vli3;
+		lzma_vli reserved_vli4;
+
+		const void *reserved_ptr1;
+		const void *reserved_ptr2;
+		const void *reserved_ptr3;
+		const void *reserved_ptr4;
+	} block;
+
+	/*
+	 * Internal data which is used to store the state of the iterator.
+	 * The exact format may vary between liblzma versions, so don't
+	 * touch these in any way.
+	 */
+	union {
+		const void *p;
+		size_t s;
+		lzma_vli v;
+	} internal[6];
+} lzma_index_iter;
+
+
+/**
+ * \brief       Operation mode for lzma_index_iter_next()
+ */
+typedef enum {
+	LZMA_INDEX_ITER_ANY             = 0,
+		/**<
+		 * \brief       Get the next Block or Stream
+		 *
+		 * Go to the next Block if the current Stream has at least
+		 * one Block left. Otherwise go to the next Stream even if
+		 * it has no Blocks. If the Stream has no Blocks
+		 * (lzma_index_iter.stream.block_count == 0),
+		 * lzma_index_iter.block will have undefined values.
+		 */
+
+	LZMA_INDEX_ITER_STREAM          = 1,
+		/**<
+		 * \brief       Get the next Stream
+		 *
+		 * Go to the next Stream even if the current Stream has
+		 * unread Blocks left. If the next Stream has at least one
+		 * Block, the iterator will point to the first Block.
+		 * If there are no Blocks, lzma_index_iter.block will have
+		 * undefined values.
+		 */
+
+	LZMA_INDEX_ITER_BLOCK           = 2,
+		/**<
+		 * \brief       Get the next Block
+		 *
+		 * Go to the next Block if the current Stream has at least
+		 * one Block left. If the current Stream has no Blocks left,
+		 * the next Stream with at least one Block is located and
+		 * the iterator will be made to point to the first Block of
+		 * that Stream.
+		 */
+
+	LZMA_INDEX_ITER_NONEMPTY_BLOCK  = 3
+		/**<
+		 * \brief       Get the next non-empty Block
+		 *
+		 * This is like LZMA_INDEX_ITER_BLOCK except that it will
+		 * skip Blocks whose Uncompressed Size is zero.
+		 */
+
+} lzma_index_iter_mode;
+
+
+/**
+ * \brief       Calculate memory usage of lzma_index
+ *
+ * On disk, the size of the Index field depends on both the number of Records
+ * stored and how big values the Records store (due to variable-length integer
+ * encoding). When the Index is kept in lzma_index structure, the memory usage
+ * depends only on the number of Records/Blocks stored in the Index(es), and
+ * in case of concatenated lzma_indexes, the number of Streams. The size in
+ * RAM is almost always significantly bigger than in the encoded form on disk.
+ *
+ * This function calculates an approximate amount of memory needed hold
+ * the given number of Streams and Blocks in lzma_index structure. This
+ * value may vary between CPU architectures and also between liblzma versions
+ * if the internal implementation is modified.
+ */
+extern LZMA_API(uint64_t) lzma_index_memusage(
+		lzma_vli streams, lzma_vli blocks) lzma_nothrow;
+
+
+/**
+ * \brief       Calculate the memory usage of an existing lzma_index
+ *
+ * This is a shorthand for lzma_index_memusage(lzma_index_stream_count(i),
+ * lzma_index_block_count(i)).
+ */
+extern LZMA_API(uint64_t) lzma_index_memused(const lzma_index *i)
+		lzma_nothrow;
+
+
+/**
+ * \brief       Allocate and initialize a new lzma_index structure
+ *
+ * \return      On success, a pointer to an empty initialized lzma_index is
+ *              returned. If allocation fails, NULL is returned.
+ */
+extern LZMA_API(lzma_index *) lzma_index_init(lzma_allocator *allocator)
+		lzma_nothrow;
+
+
+/**
+ * \brief       Deallocate lzma_index
+ *
+ * If i is NULL, this does nothing.
+ */
+extern LZMA_API(void) lzma_index_end(lzma_index *i, lzma_allocator *allocator)
+		lzma_nothrow;
+
+
+/**
+ * \brief       Add a new Block to lzma_index
+ *
+ * \param       i                 Pointer to a lzma_index structure
+ * \param       allocator         Pointer to lzma_allocator, or NULL to
+ *                                use malloc()
+ * \param       unpadded_size     Unpadded Size of a Block. This can be
+ *                                calculated with lzma_block_unpadded_size()
+ *                                after encoding or decoding the Block.
+ * \param       uncompressed_size Uncompressed Size of a Block. This can be
+ *                                taken directly from lzma_block structure
+ *                                after encoding or decoding the Block.
+ *
+ * Appending a new Block does not invalidate iterators. For example,
+ * if an iterator was pointing to the end of the lzma_index, after
+ * lzma_index_append() it is possible to read the next Block with
+ * an existing iterator.
+ *
+ * \return      - LZMA_OK
+ *              - LZMA_MEM_ERROR
+ *              - LZMA_DATA_ERROR: Compressed or uncompressed size of the
+ *                Stream or size of the Index field would grow too big.
+ *              - LZMA_PROG_ERROR
+ */
+extern LZMA_API(lzma_ret) lzma_index_append(
+		lzma_index *i, lzma_allocator *allocator,
+		lzma_vli unpadded_size, lzma_vli uncompressed_size)
+		lzma_nothrow lzma_attr_warn_unused_result;
+
+
+/**
+ * \brief       Set the Stream Flags
+ *
+ * Set the Stream Flags of the last (and typically the only) Stream
+ * in lzma_index. This can be useful when reading information from the
+ * lzma_index, because to decode Blocks, knowing the integrity check type
+ * is needed.
+ *
+ * The given Stream Flags are copied into internal preallocated structure
+ * in the lzma_index, thus the caller doesn't need to keep the *stream_flags
+ * available after calling this function.
+ *
+ * \return      - LZMA_OK
+ *              - LZMA_OPTIONS_ERROR: Unsupported stream_flags->version.
+ *              - LZMA_PROG_ERROR
+ */
+extern LZMA_API(lzma_ret) lzma_index_stream_flags(
+		lzma_index *i, const lzma_stream_flags *stream_flags)
+		lzma_nothrow lzma_attr_warn_unused_result;
+
+
+/**
+ * \brief       Get the types of integrity Checks
+ *
+ * If lzma_index_stream_flags() is used to set the Stream Flags for
+ * every Stream, lzma_index_checks() can be used to get a bitmask to
+ * indicate which Check types have been used. It can be useful e.g. if
+ * showing the Check types to the user.
+ *
+ * The bitmask is 1 << check_id, e.g. CRC32 is 1 << 1 and SHA-256 is 1 << 10.
+ */
+extern LZMA_API(uint32_t) lzma_index_checks(const lzma_index *i)
+		lzma_nothrow lzma_attr_pure;
+
+
+/**
+ * \brief       Set the amount of Stream Padding
+ *
+ * Set the amount of Stream Padding of the last (and typically the only)
+ * Stream in the lzma_index. This is needed when planning to do random-access
+ * reading within multiple concatenated Streams.
+ *
+ * By default, the amount of Stream Padding is assumed to be zero bytes.
+ *
+ * \return      - LZMA_OK
+ *              - LZMA_DATA_ERROR: The file size would grow too big.
+ *              - LZMA_PROG_ERROR
+ */
+extern LZMA_API(lzma_ret) lzma_index_stream_padding(
+		lzma_index *i, lzma_vli stream_padding)
+		lzma_nothrow lzma_attr_warn_unused_result;
+
+
+/**
+ * \brief       Get the number of Streams
+ */
+extern LZMA_API(lzma_vli) lzma_index_stream_count(const lzma_index *i)
+		lzma_nothrow lzma_attr_pure;
+
+
+/**
+ * \brief       Get the number of Blocks
+ *
+ * This returns the total number of Blocks in lzma_index. To get number
+ * of Blocks in individual Streams, use lzma_index_iter.
+ */
+extern LZMA_API(lzma_vli) lzma_index_block_count(const lzma_index *i)
+		lzma_nothrow lzma_attr_pure;
+
+
+/**
+ * \brief       Get the size of the Index field as bytes
+ *
+ * This is needed to verify the Backward Size field in the Stream Footer.
+ */
+extern LZMA_API(lzma_vli) lzma_index_size(const lzma_index *i)
+		lzma_nothrow lzma_attr_pure;
+
+
+/**
+ * \brief       Get the total size of the Stream
+ *
+ * If multiple lzma_indexes have been combined, this works as if the Blocks
+ * were in a single Stream. This is useful if you are going to combine
+ * Blocks from multiple Streams into a single new Stream.
+ */
+extern LZMA_API(lzma_vli) lzma_index_stream_size(const lzma_index *i)
+		lzma_nothrow lzma_attr_pure;
+
+
+/**
+ * \brief       Get the total size of the Blocks
+ *
+ * This doesn't include the Stream Header, Stream Footer, Stream Padding,
+ * or Index fields.
+ */
+extern LZMA_API(lzma_vli) lzma_index_total_size(const lzma_index *i)
+		lzma_nothrow lzma_attr_pure;
+
+
+/**
+ * \brief       Get the total size of the file
+ *
+ * When no lzma_indexes have been combined with lzma_index_cat() and there is
+ * no Stream Padding, this function is identical to lzma_index_stream_size().
+ * If multiple lzma_indexes have been combined, this includes also the headers
+ * of each separate Stream and the possible Stream Padding fields.
+ */
+extern LZMA_API(lzma_vli) lzma_index_file_size(const lzma_index *i)
+		lzma_nothrow lzma_attr_pure;
+
+
+/**
+ * \brief       Get the uncompressed size of the file
+ */
+extern LZMA_API(lzma_vli) lzma_index_uncompressed_size(const lzma_index *i)
+		lzma_nothrow lzma_attr_pure;
+
+
+/**
+ * \brief       Initialize an iterator
+ *
+ * \param       iter    Pointer to a lzma_index_iter structure
+ * \param       i       lzma_index to which the iterator will be associated
+ *
+ * This function associates the iterator with the given lzma_index, and calls
+ * lzma_index_iter_rewind() on the iterator.
+ *
+ * This function doesn't allocate any memory, thus there is no
+ * lzma_index_iter_end(). The iterator is valid as long as the
+ * associated lzma_index is valid, that is, until lzma_index_end() or
+ * using it as source in lzma_index_cat(). Specifically, lzma_index doesn't
+ * become invalid if new Blocks are added to it with lzma_index_append() or
+ * if it is used as the destination in lzma_index_cat().
+ *
+ * It is safe to make copies of an initialized lzma_index_iter, for example,
+ * to easily restart reading at some particular position.
+ */
+extern LZMA_API(void) lzma_index_iter_init(
+		lzma_index_iter *iter, const lzma_index *i) lzma_nothrow;
+
+
+/**
+ * \brief       Rewind the iterator
+ *
+ * Rewind the iterator so that next call to lzma_index_iter_next() will
+ * return the first Block or Stream.
+ */
+extern LZMA_API(void) lzma_index_iter_rewind(lzma_index_iter *iter)
+		lzma_nothrow;
+
+
+/**
+ * \brief       Get the next Block or Stream
+ *
+ * \param       iter    Iterator initialized with lzma_index_iter_init()
+ * \param       mode    Specify what kind of information the caller wants
+ *                      to get. See lzma_index_iter_mode for details.
+ *
+ * \return      If next Block or Stream matching the mode was found, *iter
+ *              is updated and this function returns false. If no Block or
+ *              Stream matching the mode is found, *iter is not modified
+ *              and this function returns true. If mode is set to an unknown
+ *              value, *iter is not modified and this function returns true.
+ */
+extern LZMA_API(lzma_bool) lzma_index_iter_next(
+		lzma_index_iter *iter, lzma_index_iter_mode mode)
+		lzma_nothrow lzma_attr_warn_unused_result;
+
+
+/**
+ * \brief       Locate a Block
+ *
+ * If it is possible to seek in the .xz file, it is possible to parse
+ * the Index field(s) and use lzma_index_iter_locate() to do random-access
+ * reading with granularity of Block size.
+ *
+ * \param       iter    Iterator that was earlier initialized with
+ *                      lzma_index_iter_init().
+ * \param       target  Uncompressed target offset which the caller would
+ *                      like to locate from the Stream
+ *
+ * If the target is smaller than the uncompressed size of the Stream (can be
+ * checked with lzma_index_uncompressed_size()):
+ *  - Information about the Stream and Block containing the requested
+ *    uncompressed offset is stored into *iter.
+ *  - Internal state of the iterator is adjusted so that
+ *    lzma_index_iter_next() can be used to read subsequent Blocks or Streams.
+ *  - This function returns false.
+ *
+ * If target is greater than the uncompressed size of the Stream, *iter
+ * is not modified, and this function returns true.
+ */
+extern LZMA_API(lzma_bool) lzma_index_iter_locate(
+		lzma_index_iter *iter, lzma_vli target) lzma_nothrow;
+
+
+/**
+ * \brief       Concatenate lzma_indexes
+ *
+ * Concatenating lzma_indexes is useful when doing random-access reading in
+ * multi-Stream .xz file, or when combining multiple Streams into single
+ * Stream.
+ *
+ * \param       dest      lzma_index after which src is appended
+ * \param       src       lzma_index to be appended after dest. If this
+ *                        function succeeds, the memory allocated for src
+ *                        is freed or moved to be part of dest, and all
+ *                        iterators pointing to src will become invalid.
+ * \param       allocator Custom memory allocator; can be NULL to use
+ *                        malloc() and free().
+ *
+ * \return      - LZMA_OK: lzma_indexes were concatenated successfully.
+ *                src is now a dangling pointer.
+ *              - LZMA_DATA_ERROR: *dest would grow too big.
+ *              - LZMA_MEM_ERROR
+ *              - LZMA_PROG_ERROR
+ */
+extern LZMA_API(lzma_ret) lzma_index_cat(
+		lzma_index *dest, lzma_index *src, lzma_allocator *allocator)
+		lzma_nothrow lzma_attr_warn_unused_result;
+
+
+/**
+ * \brief       Duplicate lzma_index
+ *
+ * \return      A copy of the lzma_index, or NULL if memory allocation failed.
+ */
+extern LZMA_API(lzma_index *) lzma_index_dup(
+		const lzma_index *i, lzma_allocator *allocator)
+		lzma_nothrow lzma_attr_warn_unused_result;
+
+
+/**
+ * \brief       Initialize .xz Index encoder
+ *
+ * \param       strm        Pointer to properly prepared lzma_stream
+ * \param       i           Pointer to lzma_index which should be encoded.
+ *
+ * The valid `action' values for lzma_code() are LZMA_RUN and LZMA_FINISH.
+ * It is enough to use only one of them (you can choose freely; use LZMA_RUN
+ * to support liblzma versions older than 5.0.0).
+ *
+ * \return      - LZMA_OK: Initialization succeeded, continue with lzma_code().
+ *              - LZMA_MEM_ERROR
+ *              - LZMA_PROG_ERROR
+ */
+extern LZMA_API(lzma_ret) lzma_index_encoder(
+		lzma_stream *strm, const lzma_index *i)
+		lzma_nothrow lzma_attr_warn_unused_result;
+
+
+/**
+ * \brief       Initialize .xz Index decoder
+ *
+ * \param       strm        Pointer to properly prepared lzma_stream
+ * \param       i           The decoded Index will be made available via
+ *                          this pointer. Initially this function will
+ *                          set *i to NULL (the old value is ignored). If
+ *                          decoding succeeds (lzma_code() returns
+ *                          LZMA_STREAM_END), *i will be set to point
+ *                          to a new lzma_index, which the application
+ *                          has to later free with lzma_index_end().
+ * \param       memlimit    How much memory the resulting lzma_index is
+ *                          allowed to require.
+ *
+ * The valid `action' values for lzma_code() are LZMA_RUN and LZMA_FINISH.
+ * It is enough to use only one of them (you can choose freely; use LZMA_RUN
+ * to support liblzma versions older than 5.0.0).
+ *
+ * \return      - LZMA_OK: Initialization succeeded, continue with lzma_code().
+ *              - LZMA_MEM_ERROR
+ *              - LZMA_MEMLIMIT_ERROR
+ *              - LZMA_PROG_ERROR
+ */
+extern LZMA_API(lzma_ret) lzma_index_decoder(
+		lzma_stream *strm, lzma_index **i, uint64_t memlimit)
+		lzma_nothrow lzma_attr_warn_unused_result;
+
+
+/**
+ * \brief       Single-call .xz Index encoder
+ *
+ * \param       i         lzma_index to be encoded
+ * \param       out       Beginning of the output buffer
+ * \param       out_pos   The next byte will be written to out[*out_pos].
+ *                        *out_pos is updated only if encoding succeeds.
+ * \param       out_size  Size of the out buffer; the first byte into
+ *                        which no data is written to is out[out_size].
+ *
+ * \return      - LZMA_OK: Encoding was successful.
+ *              - LZMA_BUF_ERROR: Output buffer is too small. Use
+ *                lzma_index_size() to find out how much output
+ *                space is needed.
+ *              - LZMA_PROG_ERROR
+ *
+ * \note        This function doesn't take allocator argument since all
+ *              the internal data is allocated on stack.
+ */
+extern LZMA_API(lzma_ret) lzma_index_buffer_encode(const lzma_index *i,
+		uint8_t *out, size_t *out_pos, size_t out_size) lzma_nothrow;
+
+
+/**
+ * \brief       Single-call .xz Index decoder
+ *
+ * \param       i           If decoding succeeds, *i will point to a new
+ *                          lzma_index, which the application has to
+ *                          later free with lzma_index_end(). If an error
+ *                          occurs, *i will be NULL. The old value of *i
+ *                          is always ignored and thus doesn't need to be
+ *                          initialized by the caller.
+ * \param       memlimit    Pointer to how much memory the resulting
+ *                          lzma_index is allowed to require. The value
+ *                          pointed by this pointer is modified if and only
+ *                          if LZMA_MEMLIMIT_ERROR is returned.
+ * \param       allocator   Pointer to lzma_allocator, or NULL to use malloc()
+ * \param       in          Beginning of the input buffer
+ * \param       in_pos      The next byte will be read from in[*in_pos].
+ *                          *in_pos is updated only if decoding succeeds.
+ * \param       in_size     Size of the input buffer; the first byte that
+ *                          won't be read is in[in_size].
+ *
+ * \return      - LZMA_OK: Decoding was successful.
+ *              - LZMA_MEM_ERROR
+ *              - LZMA_MEMLIMIT_ERROR: Memory usage limit was reached.
+ *                The minimum required memlimit value was stored to *memlimit.
+ *              - LZMA_DATA_ERROR
+ *              - LZMA_PROG_ERROR
+ */
+extern LZMA_API(lzma_ret) lzma_index_buffer_decode(lzma_index **i,
+		uint64_t *memlimit, lzma_allocator *allocator,
+		const uint8_t *in, size_t *in_pos, size_t in_size)
+		lzma_nothrow;
diff --git a/Utilities/cmliblzma/liblzma/api/lzma/index_hash.h b/Utilities/cmliblzma/liblzma/api/lzma/index_hash.h
new file mode 100644
index 0000000..fa2e048
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/api/lzma/index_hash.h
@@ -0,0 +1,107 @@
+/**
+ * \file        lzma/index_hash.h
+ * \brief       Validate Index by using a hash function
+ *
+ * Hashing makes it possible to use constant amount of memory to validate
+ * Index of arbitrary size.
+ */
+
+/*
+ * Author: Lasse Collin
+ *
+ * This file has been put into the public domain.
+ * You can do whatever you want with this file.
+ *
+ * See ../lzma.h for information about liblzma as a whole.
+ */
+
+#ifndef LZMA_H_INTERNAL
+#	error Never include this file directly. Use <lzma.h> instead.
+#endif
+
+/**
+ * \brief       Opaque data type to hold the Index hash
+ */
+typedef struct lzma_index_hash_s lzma_index_hash;
+
+
+/**
+ * \brief       Allocate and initialize a new lzma_index_hash structure
+ *
+ * If index_hash is NULL, a new lzma_index_hash structure is allocated,
+ * initialized, and a pointer to it returned. If allocation fails, NULL
+ * is returned.
+ *
+ * If index_hash is non-NULL, it is reinitialized and the same pointer
+ * returned. In this case, return value cannot be NULL or a different
+ * pointer than the index_hash that was given as an argument.
+ */
+extern LZMA_API(lzma_index_hash *) lzma_index_hash_init(
+		lzma_index_hash *index_hash, lzma_allocator *allocator)
+		lzma_nothrow lzma_attr_warn_unused_result;
+
+
+/**
+ * \brief       Deallocate lzma_index_hash structure
+ */
+extern LZMA_API(void) lzma_index_hash_end(
+		lzma_index_hash *index_hash, lzma_allocator *allocator)
+		lzma_nothrow;
+
+
+/**
+ * \brief       Add a new Record to an Index hash
+ *
+ * \param       index             Pointer to a lzma_index_hash structure
+ * \param       unpadded_size     Unpadded Size of a Block
+ * \param       uncompressed_size Uncompressed Size of a Block
+ *
+ * \return      - LZMA_OK
+ *              - LZMA_DATA_ERROR: Compressed or uncompressed size of the
+ *                Stream or size of the Index field would grow too big.
+ *              - LZMA_PROG_ERROR: Invalid arguments or this function is being
+ *                used when lzma_index_hash_decode() has already been used.
+ */
+extern LZMA_API(lzma_ret) lzma_index_hash_append(lzma_index_hash *index_hash,
+		lzma_vli unpadded_size, lzma_vli uncompressed_size)
+		lzma_nothrow lzma_attr_warn_unused_result;
+
+
+/**
+ * \brief       Decode and validate the Index field
+ *
+ * After telling the sizes of all Blocks with lzma_index_hash_append(),
+ * the actual Index field is decoded with this function. Specifically,
+ * once decoding of the Index field has been started, no more Records
+ * can be added using lzma_index_hash_append().
+ *
+ * This function doesn't use lzma_stream structure to pass the input data.
+ * Instead, the input buffer is specified using three arguments. This is
+ * because it matches better the internal APIs of liblzma.
+ *
+ * \param       index_hash      Pointer to a lzma_index_hash structure
+ * \param       in              Pointer to the beginning of the input buffer
+ * \param       in_pos          in[*in_pos] is the next byte to process
+ * \param       in_size         in[in_size] is the first byte not to process
+ *
+ * \return      - LZMA_OK: So far good, but more input is needed.
+ *              - LZMA_STREAM_END: Index decoded successfully and it matches
+ *                the Records given with lzma_index_hash_append().
+ *              - LZMA_DATA_ERROR: Index is corrupt or doesn't match the
+ *                information given with lzma_index_hash_append().
+ *              - LZMA_BUF_ERROR: Cannot progress because *in_pos >= in_size.
+ *              - LZMA_PROG_ERROR
+ */
+extern LZMA_API(lzma_ret) lzma_index_hash_decode(lzma_index_hash *index_hash,
+		const uint8_t *in, size_t *in_pos, size_t in_size)
+		lzma_nothrow lzma_attr_warn_unused_result;
+
+
+/**
+ * \brief       Get the size of the Index field as bytes
+ *
+ * This is needed to verify the Backward Size field in the Stream Footer.
+ */
+extern LZMA_API(lzma_vli) lzma_index_hash_size(
+		const lzma_index_hash *index_hash)
+		lzma_nothrow lzma_attr_pure;
diff --git a/Utilities/cmliblzma/liblzma/api/lzma/lzma.h b/Utilities/cmliblzma/liblzma/api/lzma/lzma.h
new file mode 100644
index 0000000..3f8e095
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/api/lzma/lzma.h
@@ -0,0 +1,420 @@
+/**
+ * \file        lzma/lzma.h
+ * \brief       LZMA1 and LZMA2 filters
+ */
+
+/*
+ * Author: Lasse Collin
+ *
+ * This file has been put into the public domain.
+ * You can do whatever you want with this file.
+ *
+ * See ../lzma.h for information about liblzma as a whole.
+ */
+
+#ifndef LZMA_H_INTERNAL
+#	error Never include this file directly. Use <lzma.h> instead.
+#endif
+
+
+/**
+ * \brief       LZMA1 Filter ID
+ *
+ * LZMA1 is the very same thing as what was called just LZMA in LZMA Utils,
+ * 7-Zip, and LZMA SDK. It's called LZMA1 here to prevent developers from
+ * accidentally using LZMA when they actually want LZMA2.
+ *
+ * LZMA1 shouldn't be used for new applications unless you _really_ know
+ * what you are doing. LZMA2 is almost always a better choice.
+ */
+#define LZMA_FILTER_LZMA1       LZMA_VLI_C(0x4000000000000001)
+
+/**
+ * \brief       LZMA2 Filter ID
+ *
+ * Usually you want this instead of LZMA1. Compared to LZMA1, LZMA2 adds
+ * support for LZMA_SYNC_FLUSH, uncompressed chunks (smaller expansion
+ * when trying to compress uncompressible data), possibility to change
+ * lc/lp/pb in the middle of encoding, and some other internal improvements.
+ */
+#define LZMA_FILTER_LZMA2       LZMA_VLI_C(0x21)
+
+
+/**
+ * \brief       Match finders
+ *
+ * Match finder has major effect on both speed and compression ratio.
+ * Usually hash chains are faster than binary trees.
+ *
+ * If you will use LZMA_SYNC_FLUSH often, the hash chains may be a better
+ * choice, because binary trees get much higher compression ratio penalty
+ * with LZMA_SYNC_FLUSH.
+ *
+ * The memory usage formulas are only rough estimates, which are closest to
+ * reality when dict_size is a power of two. The formulas are  more complex
+ * in reality, and can also change a little between liblzma versions. Use
+ * lzma_raw_encoder_memusage() to get more accurate estimate of memory usage.
+ */
+typedef enum {
+	LZMA_MF_HC3     = 0x03,
+		/**<
+		 * \brief       Hash Chain with 2- and 3-byte hashing
+		 *
+		 * Minimum nice_len: 3
+		 *
+		 * Memory usage:
+		 *  - dict_size <= 16 MiB: dict_size * 7.5
+		 *  - dict_size > 16 MiB: dict_size * 5.5 + 64 MiB
+		 */
+
+	LZMA_MF_HC4     = 0x04,
+		/**<
+		 * \brief       Hash Chain with 2-, 3-, and 4-byte hashing
+		 *
+		 * Minimum nice_len: 4
+		 *
+		 * Memory usage:
+		 *  - dict_size <= 32 MiB: dict_size * 7.5
+		 *  - dict_size > 32 MiB: dict_size * 6.5
+		 */
+
+	LZMA_MF_BT2     = 0x12,
+		/**<
+		 * \brief       Binary Tree with 2-byte hashing
+		 *
+		 * Minimum nice_len: 2
+		 *
+		 * Memory usage: dict_size * 9.5
+		 */
+
+	LZMA_MF_BT3     = 0x13,
+		/**<
+		 * \brief       Binary Tree with 2- and 3-byte hashing
+		 *
+		 * Minimum nice_len: 3
+		 *
+		 * Memory usage:
+		 *  - dict_size <= 16 MiB: dict_size * 11.5
+		 *  - dict_size > 16 MiB: dict_size * 9.5 + 64 MiB
+		 */
+
+	LZMA_MF_BT4     = 0x14
+		/**<
+		 * \brief       Binary Tree with 2-, 3-, and 4-byte hashing
+		 *
+		 * Minimum nice_len: 4
+		 *
+		 * Memory usage:
+		 *  - dict_size <= 32 MiB: dict_size * 11.5
+		 *  - dict_size > 32 MiB: dict_size * 10.5
+		 */
+} lzma_match_finder;
+
+
+/**
+ * \brief       Test if given match finder is supported
+ *
+ * Return true if the given match finder is supported by this liblzma build.
+ * Otherwise false is returned. It is safe to call this with a value that
+ * isn't listed in lzma_match_finder enumeration; the return value will be
+ * false.
+ *
+ * There is no way to list which match finders are available in this
+ * particular liblzma version and build. It would be useless, because
+ * a new match finder, which the application developer wasn't aware,
+ * could require giving additional options to the encoder that the older
+ * match finders don't need.
+ */
+extern LZMA_API(lzma_bool) lzma_mf_is_supported(lzma_match_finder match_finder)
+		lzma_nothrow lzma_attr_const;
+
+
+/**
+ * \brief       Compression modes
+ *
+ * This selects the function used to analyze the data produced by the match
+ * finder.
+ */
+typedef enum {
+	LZMA_MODE_FAST = 1,
+		/**<
+		 * \brief       Fast compression
+		 *
+		 * Fast mode is usually at its best when combined with
+		 * a hash chain match finder.
+		 */
+
+	LZMA_MODE_NORMAL = 2
+		/**<
+		 * \brief       Normal compression
+		 *
+		 * This is usually notably slower than fast mode. Use this
+		 * together with binary tree match finders to expose the
+		 * full potential of the LZMA1 or LZMA2 encoder.
+		 */
+} lzma_mode;
+
+
+/**
+ * \brief       Test if given compression mode is supported
+ *
+ * Return true if the given compression mode is supported by this liblzma
+ * build. Otherwise false is returned. It is safe to call this with a value
+ * that isn't listed in lzma_mode enumeration; the return value will be false.
+ *
+ * There is no way to list which modes are available in this particular
+ * liblzma version and build. It would be useless, because a new compression
+ * mode, which the application developer wasn't aware, could require giving
+ * additional options to the encoder that the older modes don't need.
+ */
+extern LZMA_API(lzma_bool) lzma_mode_is_supported(lzma_mode mode)
+		lzma_nothrow lzma_attr_const;
+
+
+/**
+ * \brief       Options specific to the LZMA1 and LZMA2 filters
+ *
+ * Since LZMA1 and LZMA2 share most of the code, it's simplest to share
+ * the options structure too. For encoding, all but the reserved variables
+ * need to be initialized unless specifically mentioned otherwise.
+ * lzma_lzma_preset() can be used to get a good starting point.
+ *
+ * For raw decoding, both LZMA1 and LZMA2 need dict_size, preset_dict, and
+ * preset_dict_size (if preset_dict != NULL). LZMA1 needs also lc, lp, and pb.
+ */
+typedef struct {
+	/**
+	 * \brief       Dictionary size in bytes
+	 *
+	 * Dictionary size indicates how many bytes of the recently processed
+	 * uncompressed data is kept in memory. One method to reduce size of
+	 * the uncompressed data is to store distance-length pairs, which
+	 * indicate what data to repeat from the dictionary buffer. Thus,
+	 * the bigger the dictionary, the better the compression ratio
+	 * usually is.
+	 *
+	 * Maximum size of the dictionary depends on multiple things:
+	 *  - Memory usage limit
+	 *  - Available address space (not a problem on 64-bit systems)
+	 *  - Selected match finder (encoder only)
+	 *
+	 * Currently the maximum dictionary size for encoding is 1.5 GiB
+	 * (i.e. (UINT32_C(1) << 30) + (UINT32_C(1) << 29)) even on 64-bit
+	 * systems for certain match finder implementation reasons. In the
+	 * future, there may be match finders that support bigger
+	 * dictionaries.
+	 *
+	 * Decoder already supports dictionaries up to 4 GiB - 1 B (i.e.
+	 * UINT32_MAX), so increasing the maximum dictionary size of the
+	 * encoder won't cause problems for old decoders.
+	 *
+	 * Because extremely small dictionaries sizes would have unneeded
+	 * overhead in the decoder, the minimum dictionary size is 4096 bytes.
+	 *
+	 * \note        When decoding, too big dictionary does no other harm
+	 *              than wasting memory.
+	 */
+	uint32_t dict_size;
+#	define LZMA_DICT_SIZE_MIN       UINT32_C(4096)
+#	define LZMA_DICT_SIZE_DEFAULT   (UINT32_C(1) << 23)
+
+	/**
+	 * \brief       Pointer to an initial dictionary
+	 *
+	 * It is possible to initialize the LZ77 history window using
+	 * a preset dictionary. It is useful when compressing many
+	 * similar, relatively small chunks of data independently from
+	 * each other. The preset dictionary should contain typical
+	 * strings that occur in the files being compressed. The most
+	 * probable strings should be near the end of the preset dictionary.
+	 *
+	 * This feature should be used only in special situations. For
+	 * now, it works correctly only with raw encoding and decoding.
+	 * Currently none of the container formats supported by
+	 * liblzma allow preset dictionary when decoding, thus if
+	 * you create a .xz or .lzma file with preset dictionary, it
+	 * cannot be decoded with the regular decoder functions. In the
+	 * future, the .xz format will likely get support for preset
+	 * dictionary though.
+	 */
+	const uint8_t *preset_dict;
+
+	/**
+	 * \brief       Size of the preset dictionary
+	 *
+	 * Specifies the size of the preset dictionary. If the size is
+	 * bigger than dict_size, only the last dict_size bytes are
+	 * processed.
+	 *
+	 * This variable is read only when preset_dict is not NULL.
+	 * If preset_dict is not NULL but preset_dict_size is zero,
+	 * no preset dictionary is used (identical to only setting
+	 * preset_dict to NULL).
+	 */
+	uint32_t preset_dict_size;
+
+	/**
+	 * \brief       Number of literal context bits
+	 *
+	 * How many of the highest bits of the previous uncompressed
+	 * eight-bit byte (also known as `literal') are taken into
+	 * account when predicting the bits of the next literal.
+	 *
+	 * E.g. in typical English text, an upper-case letter is
+	 * often followed by a lower-case letter, and a lower-case
+	 * letter is usually followed by another lower-case letter.
+	 * In the US-ASCII character set, the highest three bits are 010
+	 * for upper-case letters and 011 for lower-case letters.
+	 * When lc is at least 3, the literal coding can take advantage of
+	 * this property in the uncompressed data.
+	 *
+	 * There is a limit that applies to literal context bits and literal
+	 * position bits together: lc + lp <= 4. Without this limit the
+	 * decoding could become very slow, which could have security related
+	 * results in some cases like email servers doing virus scanning.
+	 * This limit also simplifies the internal implementation in liblzma.
+	 *
+	 * There may be LZMA1 streams that have lc + lp > 4 (maximum possible
+	 * lc would be 8). It is not possible to decode such streams with
+	 * liblzma.
+	 */
+	uint32_t lc;
+#	define LZMA_LCLP_MIN    0
+#	define LZMA_LCLP_MAX    4
+#	define LZMA_LC_DEFAULT  3
+
+	/**
+	 * \brief       Number of literal position bits
+	 *
+	 * lp affects what kind of alignment in the uncompressed data is
+	 * assumed when encoding literals. A literal is a single 8-bit byte.
+	 * See pb below for more information about alignment.
+	 */
+	uint32_t lp;
+#	define LZMA_LP_DEFAULT  0
+
+	/**
+	 * \brief       Number of position bits
+	 *
+	 * pb affects what kind of alignment in the uncompressed data is
+	 * assumed in general. The default means four-byte alignment
+	 * (2^ pb =2^2=4), which is often a good choice when there's
+	 * no better guess.
+	 *
+	 * When the aligment is known, setting pb accordingly may reduce
+	 * the file size a little. E.g. with text files having one-byte
+	 * alignment (US-ASCII, ISO-8859-*, UTF-8), setting pb=0 can
+	 * improve compression slightly. For UTF-16 text, pb=1 is a good
+	 * choice. If the alignment is an odd number like 3 bytes, pb=0
+	 * might be the best choice.
+	 *
+	 * Even though the assumed alignment can be adjusted with pb and
+	 * lp, LZMA1 and LZMA2 still slightly favor 16-byte alignment.
+	 * It might be worth taking into account when designing file formats
+	 * that are likely to be often compressed with LZMA1 or LZMA2.
+	 */
+	uint32_t pb;
+#	define LZMA_PB_MIN      0
+#	define LZMA_PB_MAX      4
+#	define LZMA_PB_DEFAULT  2
+
+	/** Compression mode */
+	lzma_mode mode;
+
+	/**
+	 * \brief       Nice length of a match
+	 *
+	 * This determines how many bytes the encoder compares from the match
+	 * candidates when looking for the best match. Once a match of at
+	 * least nice_len bytes long is found, the encoder stops looking for
+	 * better candidates and encodes the match. (Naturally, if the found
+	 * match is actually longer than nice_len, the actual length is
+	 * encoded; it's not truncated to nice_len.)
+	 *
+	 * Bigger values usually increase the compression ratio and
+	 * compression time. For most files, 32 to 128 is a good value,
+	 * which gives very good compression ratio at good speed.
+	 *
+	 * The exact minimum value depends on the match finder. The maximum
+	 * is 273, which is the maximum length of a match that LZMA1 and
+	 * LZMA2 can encode.
+	 */
+	uint32_t nice_len;
+
+	/** Match finder ID */
+	lzma_match_finder mf;
+
+	/**
+	 * \brief       Maximum search depth in the match finder
+	 *
+	 * For every input byte, match finder searches through the hash chain
+	 * or binary tree in a loop, each iteration going one step deeper in
+	 * the chain or tree. The searching stops if
+	 *  - a match of at least nice_len bytes long is found;
+	 *  - all match candidates from the hash chain or binary tree have
+	 *    been checked; or
+	 *  - maximum search depth is reached.
+	 *
+	 * Maximum search depth is needed to prevent the match finder from
+	 * wasting too much time in case there are lots of short match
+	 * candidates. On the other hand, stopping the search before all
+	 * candidates have been checked can reduce compression ratio.
+	 *
+	 * Setting depth to zero tells liblzma to use an automatic default
+	 * value, that depends on the selected match finder and nice_len.
+	 * The default is in the range [4, 200] or so (it may vary between
+	 * liblzma versions).
+	 *
+	 * Using a bigger depth value than the default can increase
+	 * compression ratio in some cases. There is no strict maximum value,
+	 * but high values (thousands or millions) should be used with care:
+	 * the encoder could remain fast enough with typical input, but
+	 * malicious input could cause the match finder to slow down
+	 * dramatically, possibly creating a denial of service attack.
+	 */
+	uint32_t depth;
+
+	/*
+	 * Reserved space to allow possible future extensions without
+	 * breaking the ABI. You should not touch these, because the names
+	 * of these variables may change. These are and will never be used
+	 * with the currently supported options, so it is safe to leave these
+	 * uninitialized.
+	 */
+	uint32_t reserved_int1;
+	uint32_t reserved_int2;
+	uint32_t reserved_int3;
+	uint32_t reserved_int4;
+	uint32_t reserved_int5;
+	uint32_t reserved_int6;
+	uint32_t reserved_int7;
+	uint32_t reserved_int8;
+	lzma_reserved_enum reserved_enum1;
+	lzma_reserved_enum reserved_enum2;
+	lzma_reserved_enum reserved_enum3;
+	lzma_reserved_enum reserved_enum4;
+	void *reserved_ptr1;
+	void *reserved_ptr2;
+
+} lzma_options_lzma;
+
+
+/**
+ * \brief       Set a compression preset to lzma_options_lzma structure
+ *
+ * 0 is the fastest and 9 is the slowest. These match the switches -0 .. -9
+ * of the xz command line tool. In addition, it is possible to bitwise-or
+ * flags to the preset. Currently only LZMA_PRESET_EXTREME is supported.
+ * The flags are defined in container.h, because the flags are used also
+ * with lzma_easy_encoder().
+ *
+ * The preset values are subject to changes between liblzma versions.
+ *
+ * This function is available only if LZMA1 or LZMA2 encoder has been enabled
+ * when building liblzma.
+ *
+ * \return      On success, false is returned. If the preset is not
+ *              supported, true is returned.
+ */
+extern LZMA_API(lzma_bool) lzma_lzma_preset(
+		lzma_options_lzma *options, uint32_t preset) lzma_nothrow;
diff --git a/Utilities/cmliblzma/liblzma/api/lzma/stream_flags.h b/Utilities/cmliblzma/liblzma/api/lzma/stream_flags.h
new file mode 100644
index 0000000..bbdd408
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/api/lzma/stream_flags.h
@@ -0,0 +1,223 @@
+/**
+ * \file        lzma/stream_flags.h
+ * \brief       .xz Stream Header and Stream Footer encoder and decoder
+ */
+
+/*
+ * Author: Lasse Collin
+ *
+ * This file has been put into the public domain.
+ * You can do whatever you want with this file.
+ *
+ * See ../lzma.h for information about liblzma as a whole.
+ */
+
+#ifndef LZMA_H_INTERNAL
+#	error Never include this file directly. Use <lzma.h> instead.
+#endif
+
+
+/**
+ * \brief       Size of Stream Header and Stream Footer
+ *
+ * Stream Header and Stream Footer have the same size and they are not
+ * going to change even if a newer version of the .xz file format is
+ * developed in future.
+ */
+#define LZMA_STREAM_HEADER_SIZE 12
+
+
+/**
+ * \brief       Options for encoding/decoding Stream Header and Stream Footer
+ */
+typedef struct {
+	/**
+	 * \brief       Stream Flags format version
+	 *
+	 * To prevent API and ABI breakages if new features are needed in
+	 * Stream Header or Stream Footer, a version number is used to
+	 * indicate which fields in this structure are in use. For now,
+	 * version must always be zero. With non-zero version, the
+	 * lzma_stream_header_encode() and lzma_stream_footer_encode()
+	 * will return LZMA_OPTIONS_ERROR.
+	 *
+	 * lzma_stream_header_decode() and lzma_stream_footer_decode()
+	 * will always set this to the lowest value that supports all the
+	 * features indicated by the Stream Flags field. The application
+	 * must check that the version number set by the decoding functions
+	 * is supported by the application. Otherwise it is possible that
+	 * the application will decode the Stream incorrectly.
+	 */
+	uint32_t version;
+
+	/**
+	 * \brief       Backward Size
+	 *
+	 * Backward Size must be a multiple of four bytes. In this Stream
+	 * format version, Backward Size is the size of the Index field.
+	 *
+	 * Backward Size isn't actually part of the Stream Flags field, but
+	 * it is convenient to include in this structure anyway. Backward
+	 * Size is present only in the Stream Footer. There is no need to
+	 * initialize backward_size when encoding Stream Header.
+	 *
+	 * lzma_stream_header_decode() always sets backward_size to
+	 * LZMA_VLI_UNKNOWN so that it is convenient to use
+	 * lzma_stream_flags_compare() when both Stream Header and Stream
+	 * Footer have been decoded.
+	 */
+	lzma_vli backward_size;
+#	define LZMA_BACKWARD_SIZE_MIN 4
+#	define LZMA_BACKWARD_SIZE_MAX (LZMA_VLI_C(1) << 34)
+
+	/**
+	 * \brief       Check ID
+	 *
+	 * This indicates the type of the integrity check calculated from
+	 * uncompressed data.
+	 */
+	lzma_check check;
+
+	/*
+	 * Reserved space to allow possible future extensions without
+	 * breaking the ABI. You should not touch these, because the
+	 * names of these variables may change.
+	 *
+	 * (We will never be able to use all of these since Stream Flags
+	 * is just two bytes plus Backward Size of four bytes. But it's
+	 * nice to have the proper types when they are needed.)
+	 */
+	lzma_reserved_enum reserved_enum1;
+	lzma_reserved_enum reserved_enum2;
+	lzma_reserved_enum reserved_enum3;
+	lzma_reserved_enum reserved_enum4;
+	lzma_bool reserved_bool1;
+	lzma_bool reserved_bool2;
+	lzma_bool reserved_bool3;
+	lzma_bool reserved_bool4;
+	lzma_bool reserved_bool5;
+	lzma_bool reserved_bool6;
+	lzma_bool reserved_bool7;
+	lzma_bool reserved_bool8;
+	uint32_t reserved_int1;
+	uint32_t reserved_int2;
+
+} lzma_stream_flags;
+
+
+/**
+ * \brief       Encode Stream Header
+ *
+ * \param       options     Stream Header options to be encoded.
+ *                          options->backward_size is ignored and doesn't
+ *                          need to be initialized.
+ * \param       out         Beginning of the output buffer of
+ *                          LZMA_STREAM_HEADER_SIZE bytes.
+ *
+ * \return      - LZMA_OK: Encoding was successful.
+ *              - LZMA_OPTIONS_ERROR: options->version is not supported by
+ *                this liblzma version.
+ *              - LZMA_PROG_ERROR: Invalid options.
+ */
+extern LZMA_API(lzma_ret) lzma_stream_header_encode(
+		const lzma_stream_flags *options, uint8_t *out)
+		lzma_nothrow lzma_attr_warn_unused_result;
+
+
+/**
+ * \brief       Encode Stream Footer
+ *
+ * \param       options     Stream Footer options to be encoded.
+ * \param       out         Beginning of the output buffer of
+ *                          LZMA_STREAM_HEADER_SIZE bytes.
+ *
+ * \return      - LZMA_OK: Encoding was successful.
+ *              - LZMA_OPTIONS_ERROR: options->version is not supported by
+ *                this liblzma version.
+ *              - LZMA_PROG_ERROR: Invalid options.
+ */
+extern LZMA_API(lzma_ret) lzma_stream_footer_encode(
+		const lzma_stream_flags *options, uint8_t *out)
+		lzma_nothrow lzma_attr_warn_unused_result;
+
+
+/**
+ * \brief       Decode Stream Header
+ *
+ * \param       options     Target for the decoded Stream Header options.
+ * \param       in          Beginning of the input buffer of
+ *                          LZMA_STREAM_HEADER_SIZE bytes.
+ *
+ * options->backward_size is always set to LZMA_VLI_UNKNOWN. This is to
+ * help comparing Stream Flags from Stream Header and Stream Footer with
+ * lzma_stream_flags_compare().
+ *
+ * \return      - LZMA_OK: Decoding was successful.
+ *              - LZMA_FORMAT_ERROR: Magic bytes don't match, thus the given
+ *                buffer cannot be Stream Header.
+ *              - LZMA_DATA_ERROR: CRC32 doesn't match, thus the header
+ *                is corrupt.
+ *              - LZMA_OPTIONS_ERROR: Unsupported options are present
+ *                in the header.
+ *
+ * \note        When decoding .xz files that contain multiple Streams, it may
+ *              make sense to print "file format not recognized" only if
+ *              decoding of the Stream Header of the _first_ Stream gives
+ *              LZMA_FORMAT_ERROR. If non-first Stream Header gives
+ *              LZMA_FORMAT_ERROR, the message used for LZMA_DATA_ERROR is
+ *              probably more appropriate.
+ *
+ *              For example, Stream decoder in liblzma uses LZMA_DATA_ERROR if
+ *              LZMA_FORMAT_ERROR is returned by lzma_stream_header_decode()
+ *              when decoding non-first Stream.
+ */
+extern LZMA_API(lzma_ret) lzma_stream_header_decode(
+		lzma_stream_flags *options, const uint8_t *in)
+		lzma_nothrow lzma_attr_warn_unused_result;
+
+
+/**
+ * \brief       Decode Stream Footer
+ *
+ * \param       options     Target for the decoded Stream Header options.
+ * \param       in          Beginning of the input buffer of
+ *                          LZMA_STREAM_HEADER_SIZE bytes.
+ *
+ * \return      - LZMA_OK: Decoding was successful.
+ *              - LZMA_FORMAT_ERROR: Magic bytes don't match, thus the given
+ *                buffer cannot be Stream Footer.
+ *              - LZMA_DATA_ERROR: CRC32 doesn't match, thus the Stream Footer
+ *                is corrupt.
+ *              - LZMA_OPTIONS_ERROR: Unsupported options are present
+ *                in Stream Footer.
+ *
+ * \note        If Stream Header was already decoded successfully, but
+ *              decoding Stream Footer returns LZMA_FORMAT_ERROR, the
+ *              application should probably report some other error message
+ *              than "file format not recognized", since the file more likely
+ *              is corrupt (possibly truncated). Stream decoder in liblzma
+ *              uses LZMA_DATA_ERROR in this situation.
+ */
+extern LZMA_API(lzma_ret) lzma_stream_footer_decode(
+		lzma_stream_flags *options, const uint8_t *in)
+		lzma_nothrow lzma_attr_warn_unused_result;
+
+
+/**
+ * \brief       Compare two lzma_stream_flags structures
+ *
+ * backward_size values are compared only if both are not
+ * LZMA_VLI_UNKNOWN.
+ *
+ * \return      - LZMA_OK: Both are equal. If either had backward_size set
+ *                to LZMA_VLI_UNKNOWN, backward_size values were not
+ *                compared or validated.
+ *              - LZMA_DATA_ERROR: The structures differ.
+ *              - LZMA_OPTIONS_ERROR: version in either structure is greater
+ *                than the maximum supported version (currently zero).
+ *              - LZMA_PROG_ERROR: Invalid value, e.g. invalid check or
+ *                backward_size.
+ */
+extern LZMA_API(lzma_ret) lzma_stream_flags_compare(
+		const lzma_stream_flags *a, const lzma_stream_flags *b)
+		lzma_nothrow lzma_attr_pure;
diff --git a/Utilities/cmliblzma/liblzma/api/lzma/version.h b/Utilities/cmliblzma/liblzma/api/lzma/version.h
new file mode 100644
index 0000000..66e9396
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/api/lzma/version.h
@@ -0,0 +1,121 @@
+/**
+ * \file        lzma/version.h
+ * \brief       Version number
+ */
+
+/*
+ * Author: Lasse Collin
+ *
+ * This file has been put into the public domain.
+ * You can do whatever you want with this file.
+ *
+ * See ../lzma.h for information about liblzma as a whole.
+ */
+
+#ifndef LZMA_H_INTERNAL
+#	error Never include this file directly. Use <lzma.h> instead.
+#endif
+
+
+/*
+ * Version number split into components
+ */
+#define LZMA_VERSION_MAJOR 5
+#define LZMA_VERSION_MINOR 0
+#define LZMA_VERSION_PATCH 5
+#define LZMA_VERSION_STABILITY LZMA_VERSION_STABILITY_STABLE
+
+#ifndef LZMA_VERSION_COMMIT
+#	define LZMA_VERSION_COMMIT ""
+#endif
+
+
+/*
+ * Map symbolic stability levels to integers.
+ */
+#define LZMA_VERSION_STABILITY_ALPHA 0
+#define LZMA_VERSION_STABILITY_BETA 1
+#define LZMA_VERSION_STABILITY_STABLE 2
+
+
+/**
+ * \brief       Compile-time version number
+ *
+ * The version number is of format xyyyzzzs where
+ *  - x = major
+ *  - yyy = minor
+ *  - zzz = revision
+ *  - s indicates stability: 0 = alpha, 1 = beta, 2 = stable
+ *
+ * The same xyyyzzz triplet is never reused with different stability levels.
+ * For example, if 5.1.0alpha has been released, there will never be 5.1.0beta
+ * or 5.1.0 stable.
+ *
+ * \note        The version number of liblzma has nothing to with
+ *              the version number of Igor Pavlov's LZMA SDK.
+ */
+#define LZMA_VERSION (LZMA_VERSION_MAJOR * UINT32_C(10000000) \
+		+ LZMA_VERSION_MINOR * UINT32_C(10000) \
+		+ LZMA_VERSION_PATCH * UINT32_C(10) \
+		+ LZMA_VERSION_STABILITY)
+
+
+/*
+ * Macros to construct the compile-time version string
+ */
+#if LZMA_VERSION_STABILITY == LZMA_VERSION_STABILITY_ALPHA
+#	define LZMA_VERSION_STABILITY_STRING "alpha"
+#elif LZMA_VERSION_STABILITY == LZMA_VERSION_STABILITY_BETA
+#	define LZMA_VERSION_STABILITY_STRING "beta"
+#elif LZMA_VERSION_STABILITY == LZMA_VERSION_STABILITY_STABLE
+#	define LZMA_VERSION_STABILITY_STRING ""
+#else
+#	error Incorrect LZMA_VERSION_STABILITY
+#endif
+
+#define LZMA_VERSION_STRING_C_(major, minor, patch, stability, commit) \
+		#major "." #minor "." #patch stability commit
+
+#define LZMA_VERSION_STRING_C(major, minor, patch, stability, commit) \
+		LZMA_VERSION_STRING_C_(major, minor, patch, stability, commit)
+
+
+/**
+ * \brief       Compile-time version as a string
+ *
+ * This can be for example "4.999.5alpha", "4.999.8beta", or "5.0.0" (stable
+ * versions don't have any "stable" suffix). In future, a snapshot built
+ * from source code repository may include an additional suffix, for example
+ * "4.999.8beta-21-g1d92". The commit ID won't be available in numeric form
+ * in LZMA_VERSION macro.
+ */
+#define LZMA_VERSION_STRING LZMA_VERSION_STRING_C( \
+		LZMA_VERSION_MAJOR, LZMA_VERSION_MINOR, \
+		LZMA_VERSION_PATCH, LZMA_VERSION_STABILITY_STRING, \
+		LZMA_VERSION_COMMIT)
+
+
+/* #ifndef is needed for use with windres (MinGW or Cygwin). */
+#ifndef LZMA_H_INTERNAL_RC
+
+/**
+ * \brief       Run-time version number as an integer
+ *
+ * Return the value of LZMA_VERSION macro at the compile time of liblzma.
+ * This allows the application to compare if it was built against the same,
+ * older, or newer version of liblzma that is currently running.
+ */
+extern LZMA_API(uint32_t) lzma_version_number(void)
+		lzma_nothrow lzma_attr_const;
+
+
+/**
+ * \brief       Run-time version as a string
+ *
+ * This function may be useful if you want to display which version of
+ * liblzma your application is currently using.
+ */
+extern LZMA_API(const char *) lzma_version_string(void)
+		lzma_nothrow lzma_attr_const;
+
+#endif
diff --git a/Utilities/cmliblzma/liblzma/api/lzma/vli.h b/Utilities/cmliblzma/liblzma/api/lzma/vli.h
new file mode 100644
index 0000000..9ad13f2
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/api/lzma/vli.h
@@ -0,0 +1,166 @@
+/**
+ * \file        lzma/vli.h
+ * \brief       Variable-length integer handling
+ *
+ * In the .xz format, most integers are encoded in a variable-length
+ * representation, which is sometimes called little endian base-128 encoding.
+ * This saves space when smaller values are more likely than bigger values.
+ *
+ * The encoding scheme encodes seven bits to every byte, using minimum
+ * number of bytes required to represent the given value. Encodings that use
+ * non-minimum number of bytes are invalid, thus every integer has exactly
+ * one encoded representation. The maximum number of bits in a VLI is 63,
+ * thus the vli argument must be less than or equal to UINT64_MAX / 2. You
+ * should use LZMA_VLI_MAX for clarity.
+ */
+
+/*
+ * Author: Lasse Collin
+ *
+ * This file has been put into the public domain.
+ * You can do whatever you want with this file.
+ *
+ * See ../lzma.h for information about liblzma as a whole.
+ */
+
+#ifndef LZMA_H_INTERNAL
+#	error Never include this file directly. Use <lzma.h> instead.
+#endif
+
+
+/**
+ * \brief       Maximum supported value of a variable-length integer
+ */
+#define LZMA_VLI_MAX (UINT64_MAX / 2)
+
+/**
+ * \brief       VLI value to denote that the value is unknown
+ */
+#define LZMA_VLI_UNKNOWN UINT64_MAX
+
+/**
+ * \brief       Maximum supported encoded length of variable length integers
+ */
+#define LZMA_VLI_BYTES_MAX 9
+
+/**
+ * \brief       VLI constant suffix
+ */
+#define LZMA_VLI_C(n) UINT64_C(n)
+
+
+/**
+ * \brief       Variable-length integer type
+ *
+ * Valid VLI values are in the range [0, LZMA_VLI_MAX]. Unknown value is
+ * indicated with LZMA_VLI_UNKNOWN, which is the maximum value of the
+ * underlaying integer type.
+ *
+ * lzma_vli will be uint64_t for the foreseeable future. If a bigger size
+ * is needed in the future, it is guaranteed that 2 * LZMA_VLI_MAX will
+ * not overflow lzma_vli. This simplifies integer overflow detection.
+ */
+typedef uint64_t lzma_vli;
+
+
+/**
+ * \brief       Validate a variable-length integer
+ *
+ * This is useful to test that application has given acceptable values
+ * for example in the uncompressed_size and compressed_size variables.
+ *
+ * \return      True if the integer is representable as VLI or if it
+ *              indicates unknown value.
+ */
+#define lzma_vli_is_valid(vli) \
+	((vli) <= LZMA_VLI_MAX || (vli) == LZMA_VLI_UNKNOWN)
+
+
+/**
+ * \brief       Encode a variable-length integer
+ *
+ * This function has two modes: single-call and multi-call. Single-call mode
+ * encodes the whole integer at once; it is an error if the output buffer is
+ * too small. Multi-call mode saves the position in *vli_pos, and thus it is
+ * possible to continue encoding if the buffer becomes full before the whole
+ * integer has been encoded.
+ *
+ * \param       vli       Integer to be encoded
+ * \param       vli_pos   How many VLI-encoded bytes have already been written
+ *                        out. When starting to encode a new integer in
+ *                        multi-call mode, *vli_pos must be set to zero.
+ *                        To use single-call encoding, set vli_pos to NULL.
+ * \param       out       Beginning of the output buffer
+ * \param       out_pos   The next byte will be written to out[*out_pos].
+ * \param       out_size  Size of the out buffer; the first byte into
+ *                        which no data is written to is out[out_size].
+ *
+ * \return      Slightly different return values are used in multi-call and
+ *              single-call modes.
+ *
+ *              Single-call (vli_pos == NULL):
+ *              - LZMA_OK: Integer successfully encoded.
+ *              - LZMA_PROG_ERROR: Arguments are not sane. This can be due
+ *                to too little output space; single-call mode doesn't use
+ *                LZMA_BUF_ERROR, since the application should have checked
+ *                the encoded size with lzma_vli_size().
+ *
+ *              Multi-call (vli_pos != NULL):
+ *              - LZMA_OK: So far all OK, but the integer is not
+ *                completely written out yet.
+ *              - LZMA_STREAM_END: Integer successfully encoded.
+ *              - LZMA_BUF_ERROR: No output space was provided.
+ *              - LZMA_PROG_ERROR: Arguments are not sane.
+ */
+extern LZMA_API(lzma_ret) lzma_vli_encode(lzma_vli vli, size_t *vli_pos,
+		uint8_t *out, size_t *out_pos, size_t out_size) lzma_nothrow;
+
+
+/**
+ * \brief       Decode a variable-length integer
+ *
+ * Like lzma_vli_encode(), this function has single-call and multi-call modes.
+ *
+ * \param       vli       Pointer to decoded integer. The decoder will
+ *                        initialize it to zero when *vli_pos == 0, so
+ *                        application isn't required to initialize *vli.
+ * \param       vli_pos   How many bytes have already been decoded. When
+ *                        starting to decode a new integer in multi-call
+ *                        mode, *vli_pos must be initialized to zero. To
+ *                        use single-call decoding, set vli_pos to NULL.
+ * \param       in        Beginning of the input buffer
+ * \param       in_pos    The next byte will be read from in[*in_pos].
+ * \param       in_size   Size of the input buffer; the first byte that
+ *                        won't be read is in[in_size].
+ *
+ * \return      Slightly different return values are used in multi-call and
+ *              single-call modes.
+ *
+ *              Single-call (vli_pos == NULL):
+ *              - LZMA_OK: Integer successfully decoded.
+ *              - LZMA_DATA_ERROR: Integer is corrupt. This includes hitting
+ *                the end of the input buffer before the whole integer was
+ *                decoded; providing no input at all will use LZMA_DATA_ERROR.
+ *              - LZMA_PROG_ERROR: Arguments are not sane.
+ *
+ *              Multi-call (vli_pos != NULL):
+ *              - LZMA_OK: So far all OK, but the integer is not
+ *                completely decoded yet.
+ *              - LZMA_STREAM_END: Integer successfully decoded.
+ *              - LZMA_DATA_ERROR: Integer is corrupt.
+ *              - LZMA_BUF_ERROR: No input was provided.
+ *              - LZMA_PROG_ERROR: Arguments are not sane.
+ */
+extern LZMA_API(lzma_ret) lzma_vli_decode(lzma_vli *vli, size_t *vli_pos,
+		const uint8_t *in, size_t *in_pos, size_t in_size)
+		lzma_nothrow;
+
+
+/**
+ * \brief       Get the number of bytes required to encode a VLI
+ *
+ * \return      Number of bytes on success (1-9). If vli isn't valid,
+ *              zero is returned.
+ */
+extern LZMA_API(uint32_t) lzma_vli_size(lzma_vli vli)
+		lzma_nothrow lzma_attr_pure;
diff --git a/Utilities/cmliblzma/liblzma/check/check.c b/Utilities/cmliblzma/liblzma/check/check.c
new file mode 100644
index 0000000..979b0a8
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/check/check.c
@@ -0,0 +1,174 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       check.c
+/// \brief      Single API to access different integrity checks
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "check.h"
+
+
+extern LZMA_API(lzma_bool)
+lzma_check_is_supported(lzma_check type)
+{
+	static const lzma_bool available_checks[LZMA_CHECK_ID_MAX + 1] = {
+		true,   // LZMA_CHECK_NONE
+
+#ifdef HAVE_CHECK_CRC32
+		true,
+#else
+		false,
+#endif
+
+		false,  // Reserved
+		false,  // Reserved
+
+#ifdef HAVE_CHECK_CRC64
+		true,
+#else
+		false,
+#endif
+
+		false,  // Reserved
+		false,  // Reserved
+		false,  // Reserved
+		false,  // Reserved
+		false,  // Reserved
+
+#ifdef HAVE_CHECK_SHA256
+		true,
+#else
+		false,
+#endif
+
+		false,  // Reserved
+		false,  // Reserved
+		false,  // Reserved
+		false,  // Reserved
+		false,  // Reserved
+	};
+
+	if ((unsigned int)(type) > LZMA_CHECK_ID_MAX)
+		return false;
+
+	return available_checks[(unsigned int)(type)];
+}
+
+
+extern LZMA_API(uint32_t)
+lzma_check_size(lzma_check type)
+{
+	// See file-format.txt section 2.1.1.2.
+	static const uint8_t check_sizes[LZMA_CHECK_ID_MAX + 1] = {
+		0,
+		4, 4, 4,
+		8, 8, 8,
+		16, 16, 16,
+		32, 32, 32,
+		64, 64, 64
+	};
+
+	if ((unsigned int)(type) > LZMA_CHECK_ID_MAX)
+		return UINT32_MAX;
+
+	return check_sizes[(unsigned int)(type)];
+}
+
+
+extern void
+lzma_check_init(lzma_check_state *check, lzma_check type)
+{
+	switch (type) {
+	case LZMA_CHECK_NONE:
+		break;
+
+#ifdef HAVE_CHECK_CRC32
+	case LZMA_CHECK_CRC32:
+		check->state.crc32 = 0;
+		break;
+#endif
+
+#ifdef HAVE_CHECK_CRC64
+	case LZMA_CHECK_CRC64:
+		check->state.crc64 = 0;
+		break;
+#endif
+
+#ifdef HAVE_CHECK_SHA256
+	case LZMA_CHECK_SHA256:
+		lzma_sha256_init(check);
+		break;
+#endif
+
+	default:
+		break;
+	}
+
+	return;
+}
+
+
+extern void
+lzma_check_update(lzma_check_state *check, lzma_check type,
+		const uint8_t *buf, size_t size)
+{
+	switch (type) {
+#ifdef HAVE_CHECK_CRC32
+	case LZMA_CHECK_CRC32:
+		check->state.crc32 = lzma_crc32(buf, size, check->state.crc32);
+		break;
+#endif
+
+#ifdef HAVE_CHECK_CRC64
+	case LZMA_CHECK_CRC64:
+		check->state.crc64 = lzma_crc64(buf, size, check->state.crc64);
+		break;
+#endif
+
+#ifdef HAVE_CHECK_SHA256
+	case LZMA_CHECK_SHA256:
+		lzma_sha256_update(buf, size, check);
+		break;
+#endif
+
+	default:
+		break;
+	}
+
+	return;
+}
+
+
+extern void
+lzma_check_finish(lzma_check_state *check, lzma_check type)
+{
+	switch (type) {
+#ifdef HAVE_CHECK_CRC32
+	case LZMA_CHECK_CRC32:
+		check->buffer.u32[0] = conv32le(check->state.crc32);
+		break;
+#endif
+
+#ifdef HAVE_CHECK_CRC64
+	case LZMA_CHECK_CRC64:
+		check->buffer.u64[0] = conv64le(check->state.crc64);
+		break;
+#endif
+
+#ifdef HAVE_CHECK_SHA256
+	case LZMA_CHECK_SHA256:
+		lzma_sha256_finish(check);
+		break;
+#endif
+
+	default:
+		break;
+	}
+
+	return;
+}
diff --git a/Utilities/cmliblzma/liblzma/check/check.h b/Utilities/cmliblzma/liblzma/check/check.h
new file mode 100644
index 0000000..e100d2b
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/check/check.h
@@ -0,0 +1,95 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       check.h
+/// \brief      Internal API to different integrity check functions
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#ifndef LZMA_CHECK_H
+#define LZMA_CHECK_H
+
+#include "common.h"
+
+
+// Index hashing needs the best possible hash function (preferably
+// a cryptographic hash) for maximum reliability.
+#if defined(HAVE_CHECK_SHA256)
+#	define LZMA_CHECK_BEST LZMA_CHECK_SHA256
+#elif defined(HAVE_CHECK_CRC64)
+#	define LZMA_CHECK_BEST LZMA_CHECK_CRC64
+#else
+#	define LZMA_CHECK_BEST LZMA_CHECK_CRC32
+#endif
+
+
+/// \brief      Structure to hold internal state of the check being calculated
+///
+/// \note       This is not in the public API because this structure may
+///             change in future if new integrity check algorithms are added.
+typedef struct {
+	/// Buffer to hold the final result and a temporary buffer for SHA256.
+	union {
+		uint8_t u8[64];
+		uint32_t u32[16];
+		uint64_t u64[8];
+	} buffer;
+
+	/// Check-specific data
+	union {
+		uint32_t crc32;
+		uint64_t crc64;
+
+		struct {
+			/// Internal state
+			uint32_t state[8];
+
+			/// Size of the message excluding padding
+			uint64_t size;
+		} sha256;
+	} state;
+
+} lzma_check_state;
+
+
+/// lzma_crc32_table[0] is needed by LZ encoder so we need to keep
+/// the array two-dimensional.
+#ifdef HAVE_SMALL
+extern uint32_t lzma_crc32_table[1][256];
+extern void lzma_crc32_init(void);
+#else
+extern const uint32_t lzma_crc32_table[8][256];
+extern const uint64_t lzma_crc64_table[4][256];
+#endif
+
+
+/// \brief      Initialize *check depending on type
+///
+/// \return     LZMA_OK on success. LZMA_UNSUPPORTED_CHECK if the type is not
+///             supported by the current version or build of liblzma.
+///             LZMA_PROG_ERROR if type > LZMA_CHECK_ID_MAX.
+extern void lzma_check_init(lzma_check_state *check, lzma_check type);
+
+/// Update the check state
+extern void lzma_check_update(lzma_check_state *check, lzma_check type,
+		const uint8_t *buf, size_t size);
+
+/// Finish the check calculation and store the result to check->buffer.u8.
+extern void lzma_check_finish(lzma_check_state *check, lzma_check type);
+
+
+/// Prepare SHA-256 state for new input.
+extern void lzma_sha256_init(lzma_check_state *check);
+
+/// Update the SHA-256 hash state
+extern void lzma_sha256_update(
+		const uint8_t *buf, size_t size, lzma_check_state *check);
+
+/// Finish the SHA-256 calculation and store the result to check->buffer.u8.
+extern void lzma_sha256_finish(lzma_check_state *check);
+
+#endif
diff --git a/Utilities/cmliblzma/liblzma/check/crc32_fast.c b/Utilities/cmliblzma/liblzma/check/crc32_fast.c
new file mode 100644
index 0000000..13f65b4
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/check/crc32_fast.c
@@ -0,0 +1,86 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       crc32.c
+/// \brief      CRC32 calculation
+///
+/// Calculate the CRC32 using the slice-by-eight algorithm.
+/// It is explained in this document:
+/// http://www.intel.com/technology/comms/perfnet/download/CRC_generators.pdf
+/// The code in this file is not the same as in Intel's paper, but
+/// the basic principle is identical.
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "check.h"
+#include "crc_macros.h"
+
+
+// If you make any changes, do some bench marking! Seemingly unrelated
+// changes can very easily ruin the performance (and very probably is
+// very compiler dependent).
+extern LZMA_API(uint32_t)
+lzma_crc32(const uint8_t *buf, size_t size, uint32_t crc)
+{
+	crc = ~crc;
+
+#ifdef WORDS_BIGENDIAN
+	crc = bswap32(crc);
+#endif
+
+	if (size > 8) {
+		const uint8_t * limit;
+
+		// Fix the alignment, if needed. The if statement above
+		// ensures that this won't read past the end of buf[].
+		while ((uintptr_t)(buf) & 7) {
+			crc = lzma_crc32_table[0][*buf++ ^ A(crc)] ^ S8(crc);
+			--size;
+		}
+
+		// Calculate the position where to stop.
+		limit = buf + (size & ~(size_t)(7));
+
+		// Calculate how many bytes must be calculated separately
+		// before returning the result.
+		size &= (size_t)(7);
+
+		// Calculate the CRC32 using the slice-by-eight algorithm.
+		while (buf < limit) {
+			uint32_t tmp;
+
+			crc ^= *(const uint32_t *)(buf);
+			buf += 4;
+
+			crc = lzma_crc32_table[7][A(crc)]
+			    ^ lzma_crc32_table[6][B(crc)]
+			    ^ lzma_crc32_table[5][C(crc)]
+			    ^ lzma_crc32_table[4][D(crc)];
+
+			tmp = *(const uint32_t *)(buf);
+			buf += 4;
+
+			// At least with some compilers, it is critical for
+			// performance, that the crc variable is XORed
+			// between the two table-lookup pairs.
+			crc = lzma_crc32_table[3][A(tmp)]
+			    ^ lzma_crc32_table[2][B(tmp)]
+			    ^ crc
+			    ^ lzma_crc32_table[1][C(tmp)]
+			    ^ lzma_crc32_table[0][D(tmp)];
+		}
+	}
+
+	while (size-- != 0)
+		crc = lzma_crc32_table[0][*buf++ ^ A(crc)] ^ S8(crc);
+
+#ifdef WORDS_BIGENDIAN
+	crc = bswap32(crc);
+#endif
+
+	return ~crc;
+}
diff --git a/Utilities/cmliblzma/liblzma/check/crc32_small.c b/Utilities/cmliblzma/liblzma/check/crc32_small.c
new file mode 100644
index 0000000..5f8a328
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/check/crc32_small.c
@@ -0,0 +1,61 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       crc32_small.c
+/// \brief      CRC32 calculation (size-optimized)
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "check.h"
+
+
+uint32_t lzma_crc32_table[1][256];
+
+
+static void
+crc32_init(void)
+{
+	static const uint32_t poly32 = UINT32_C(0xEDB88320);
+
+	for (size_t b = 0; b < 256; ++b) {
+		uint32_t r = b;
+		for (size_t i = 0; i < 8; ++i) {
+			if (r & 1)
+				r = (r >> 1) ^ poly32;
+			else
+				r >>= 1;
+		}
+
+		lzma_crc32_table[0][b] = r;
+	}
+
+	return;
+}
+
+
+extern void
+lzma_crc32_init(void)
+{
+	mythread_once(crc32_init);
+	return;
+}
+
+
+extern LZMA_API(uint32_t)
+lzma_crc32(const uint8_t *buf, size_t size, uint32_t crc)
+{
+	lzma_crc32_init();
+
+	crc = ~crc;
+
+	while (size != 0) {
+		crc = lzma_crc32_table[0][*buf++ ^ (crc & 0xFF)] ^ (crc >> 8);
+		--size;
+	}
+
+	return ~crc;
+}
diff --git a/Utilities/cmliblzma/liblzma/check/crc32_table.c b/Utilities/cmliblzma/liblzma/check/crc32_table.c
new file mode 100644
index 0000000..368874e
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/check/crc32_table.c
@@ -0,0 +1,19 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       crc32_table.c
+/// \brief      Precalculated CRC32 table with correct endianness
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "common.h"
+
+#ifdef WORDS_BIGENDIAN
+#	include "crc32_table_be.h"
+#else
+#	include "crc32_table_le.h"
+#endif
diff --git a/Utilities/cmliblzma/liblzma/check/crc32_table_be.h b/Utilities/cmliblzma/liblzma/check/crc32_table_be.h
new file mode 100644
index 0000000..c483cb6
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/check/crc32_table_be.h
@@ -0,0 +1,525 @@
+/* This file has been automatically generated by crc32_tablegen.c. */
+
+const uint32_t lzma_crc32_table[8][256] = {
+	{
+		0x00000000, 0x96300777, 0x2C610EEE, 0xBA510999,
+		0x19C46D07, 0x8FF46A70, 0x35A563E9, 0xA395649E,
+		0x3288DB0E, 0xA4B8DC79, 0x1EE9D5E0, 0x88D9D297,
+		0x2B4CB609, 0xBD7CB17E, 0x072DB8E7, 0x911DBF90,
+		0x6410B71D, 0xF220B06A, 0x4871B9F3, 0xDE41BE84,
+		0x7DD4DA1A, 0xEBE4DD6D, 0x51B5D4F4, 0xC785D383,
+		0x56986C13, 0xC0A86B64, 0x7AF962FD, 0xECC9658A,
+		0x4F5C0114, 0xD96C0663, 0x633D0FFA, 0xF50D088D,
+		0xC8206E3B, 0x5E10694C, 0xE44160D5, 0x727167A2,
+		0xD1E4033C, 0x47D4044B, 0xFD850DD2, 0x6BB50AA5,
+		0xFAA8B535, 0x6C98B242, 0xD6C9BBDB, 0x40F9BCAC,
+		0xE36CD832, 0x755CDF45, 0xCF0DD6DC, 0x593DD1AB,
+		0xAC30D926, 0x3A00DE51, 0x8051D7C8, 0x1661D0BF,
+		0xB5F4B421, 0x23C4B356, 0x9995BACF, 0x0FA5BDB8,
+		0x9EB80228, 0x0888055F, 0xB2D90CC6, 0x24E90BB1,
+		0x877C6F2F, 0x114C6858, 0xAB1D61C1, 0x3D2D66B6,
+		0x9041DC76, 0x0671DB01, 0xBC20D298, 0x2A10D5EF,
+		0x8985B171, 0x1FB5B606, 0xA5E4BF9F, 0x33D4B8E8,
+		0xA2C90778, 0x34F9000F, 0x8EA80996, 0x18980EE1,
+		0xBB0D6A7F, 0x2D3D6D08, 0x976C6491, 0x015C63E6,
+		0xF4516B6B, 0x62616C1C, 0xD8306585, 0x4E0062F2,
+		0xED95066C, 0x7BA5011B, 0xC1F40882, 0x57C40FF5,
+		0xC6D9B065, 0x50E9B712, 0xEAB8BE8B, 0x7C88B9FC,
+		0xDF1DDD62, 0x492DDA15, 0xF37CD38C, 0x654CD4FB,
+		0x5861B24D, 0xCE51B53A, 0x7400BCA3, 0xE230BBD4,
+		0x41A5DF4A, 0xD795D83D, 0x6DC4D1A4, 0xFBF4D6D3,
+		0x6AE96943, 0xFCD96E34, 0x468867AD, 0xD0B860DA,
+		0x732D0444, 0xE51D0333, 0x5F4C0AAA, 0xC97C0DDD,
+		0x3C710550, 0xAA410227, 0x10100BBE, 0x86200CC9,
+		0x25B56857, 0xB3856F20, 0x09D466B9, 0x9FE461CE,
+		0x0EF9DE5E, 0x98C9D929, 0x2298D0B0, 0xB4A8D7C7,
+		0x173DB359, 0x810DB42E, 0x3B5CBDB7, 0xAD6CBAC0,
+		0x2083B8ED, 0xB6B3BF9A, 0x0CE2B603, 0x9AD2B174,
+		0x3947D5EA, 0xAF77D29D, 0x1526DB04, 0x8316DC73,
+		0x120B63E3, 0x843B6494, 0x3E6A6D0D, 0xA85A6A7A,
+		0x0BCF0EE4, 0x9DFF0993, 0x27AE000A, 0xB19E077D,
+		0x44930FF0, 0xD2A30887, 0x68F2011E, 0xFEC20669,
+		0x5D5762F7, 0xCB676580, 0x71366C19, 0xE7066B6E,
+		0x761BD4FE, 0xE02BD389, 0x5A7ADA10, 0xCC4ADD67,
+		0x6FDFB9F9, 0xF9EFBE8E, 0x43BEB717, 0xD58EB060,
+		0xE8A3D6D6, 0x7E93D1A1, 0xC4C2D838, 0x52F2DF4F,
+		0xF167BBD1, 0x6757BCA6, 0xDD06B53F, 0x4B36B248,
+		0xDA2B0DD8, 0x4C1B0AAF, 0xF64A0336, 0x607A0441,
+		0xC3EF60DF, 0x55DF67A8, 0xEF8E6E31, 0x79BE6946,
+		0x8CB361CB, 0x1A8366BC, 0xA0D26F25, 0x36E26852,
+		0x95770CCC, 0x03470BBB, 0xB9160222, 0x2F260555,
+		0xBE3BBAC5, 0x280BBDB2, 0x925AB42B, 0x046AB35C,
+		0xA7FFD7C2, 0x31CFD0B5, 0x8B9ED92C, 0x1DAEDE5B,
+		0xB0C2649B, 0x26F263EC, 0x9CA36A75, 0x0A936D02,
+		0xA906099C, 0x3F360EEB, 0x85670772, 0x13570005,
+		0x824ABF95, 0x147AB8E2, 0xAE2BB17B, 0x381BB60C,
+		0x9B8ED292, 0x0DBED5E5, 0xB7EFDC7C, 0x21DFDB0B,
+		0xD4D2D386, 0x42E2D4F1, 0xF8B3DD68, 0x6E83DA1F,
+		0xCD16BE81, 0x5B26B9F6, 0xE177B06F, 0x7747B718,
+		0xE65A0888, 0x706A0FFF, 0xCA3B0666, 0x5C0B0111,
+		0xFF9E658F, 0x69AE62F8, 0xD3FF6B61, 0x45CF6C16,
+		0x78E20AA0, 0xEED20DD7, 0x5483044E, 0xC2B30339,
+		0x612667A7, 0xF71660D0, 0x4D476949, 0xDB776E3E,
+		0x4A6AD1AE, 0xDC5AD6D9, 0x660BDF40, 0xF03BD837,
+		0x53AEBCA9, 0xC59EBBDE, 0x7FCFB247, 0xE9FFB530,
+		0x1CF2BDBD, 0x8AC2BACA, 0x3093B353, 0xA6A3B424,
+		0x0536D0BA, 0x9306D7CD, 0x2957DE54, 0xBF67D923,
+		0x2E7A66B3, 0xB84A61C4, 0x021B685D, 0x942B6F2A,
+		0x37BE0BB4, 0xA18E0CC3, 0x1BDF055A, 0x8DEF022D
+	}, {
+		0x00000000, 0x41311B19, 0x82623632, 0xC3532D2B,
+		0x04C56C64, 0x45F4777D, 0x86A75A56, 0xC796414F,
+		0x088AD9C8, 0x49BBC2D1, 0x8AE8EFFA, 0xCBD9F4E3,
+		0x0C4FB5AC, 0x4D7EAEB5, 0x8E2D839E, 0xCF1C9887,
+		0x5112C24A, 0x1023D953, 0xD370F478, 0x9241EF61,
+		0x55D7AE2E, 0x14E6B537, 0xD7B5981C, 0x96848305,
+		0x59981B82, 0x18A9009B, 0xDBFA2DB0, 0x9ACB36A9,
+		0x5D5D77E6, 0x1C6C6CFF, 0xDF3F41D4, 0x9E0E5ACD,
+		0xA2248495, 0xE3159F8C, 0x2046B2A7, 0x6177A9BE,
+		0xA6E1E8F1, 0xE7D0F3E8, 0x2483DEC3, 0x65B2C5DA,
+		0xAAAE5D5D, 0xEB9F4644, 0x28CC6B6F, 0x69FD7076,
+		0xAE6B3139, 0xEF5A2A20, 0x2C09070B, 0x6D381C12,
+		0xF33646DF, 0xB2075DC6, 0x715470ED, 0x30656BF4,
+		0xF7F32ABB, 0xB6C231A2, 0x75911C89, 0x34A00790,
+		0xFBBC9F17, 0xBA8D840E, 0x79DEA925, 0x38EFB23C,
+		0xFF79F373, 0xBE48E86A, 0x7D1BC541, 0x3C2ADE58,
+		0x054F79F0, 0x447E62E9, 0x872D4FC2, 0xC61C54DB,
+		0x018A1594, 0x40BB0E8D, 0x83E823A6, 0xC2D938BF,
+		0x0DC5A038, 0x4CF4BB21, 0x8FA7960A, 0xCE968D13,
+		0x0900CC5C, 0x4831D745, 0x8B62FA6E, 0xCA53E177,
+		0x545DBBBA, 0x156CA0A3, 0xD63F8D88, 0x970E9691,
+		0x5098D7DE, 0x11A9CCC7, 0xD2FAE1EC, 0x93CBFAF5,
+		0x5CD76272, 0x1DE6796B, 0xDEB55440, 0x9F844F59,
+		0x58120E16, 0x1923150F, 0xDA703824, 0x9B41233D,
+		0xA76BFD65, 0xE65AE67C, 0x2509CB57, 0x6438D04E,
+		0xA3AE9101, 0xE29F8A18, 0x21CCA733, 0x60FDBC2A,
+		0xAFE124AD, 0xEED03FB4, 0x2D83129F, 0x6CB20986,
+		0xAB2448C9, 0xEA1553D0, 0x29467EFB, 0x687765E2,
+		0xF6793F2F, 0xB7482436, 0x741B091D, 0x352A1204,
+		0xF2BC534B, 0xB38D4852, 0x70DE6579, 0x31EF7E60,
+		0xFEF3E6E7, 0xBFC2FDFE, 0x7C91D0D5, 0x3DA0CBCC,
+		0xFA368A83, 0xBB07919A, 0x7854BCB1, 0x3965A7A8,
+		0x4B98833B, 0x0AA99822, 0xC9FAB509, 0x88CBAE10,
+		0x4F5DEF5F, 0x0E6CF446, 0xCD3FD96D, 0x8C0EC274,
+		0x43125AF3, 0x022341EA, 0xC1706CC1, 0x804177D8,
+		0x47D73697, 0x06E62D8E, 0xC5B500A5, 0x84841BBC,
+		0x1A8A4171, 0x5BBB5A68, 0x98E87743, 0xD9D96C5A,
+		0x1E4F2D15, 0x5F7E360C, 0x9C2D1B27, 0xDD1C003E,
+		0x120098B9, 0x533183A0, 0x9062AE8B, 0xD153B592,
+		0x16C5F4DD, 0x57F4EFC4, 0x94A7C2EF, 0xD596D9F6,
+		0xE9BC07AE, 0xA88D1CB7, 0x6BDE319C, 0x2AEF2A85,
+		0xED796BCA, 0xAC4870D3, 0x6F1B5DF8, 0x2E2A46E1,
+		0xE136DE66, 0xA007C57F, 0x6354E854, 0x2265F34D,
+		0xE5F3B202, 0xA4C2A91B, 0x67918430, 0x26A09F29,
+		0xB8AEC5E4, 0xF99FDEFD, 0x3ACCF3D6, 0x7BFDE8CF,
+		0xBC6BA980, 0xFD5AB299, 0x3E099FB2, 0x7F3884AB,
+		0xB0241C2C, 0xF1150735, 0x32462A1E, 0x73773107,
+		0xB4E17048, 0xF5D06B51, 0x3683467A, 0x77B25D63,
+		0x4ED7FACB, 0x0FE6E1D2, 0xCCB5CCF9, 0x8D84D7E0,
+		0x4A1296AF, 0x0B238DB6, 0xC870A09D, 0x8941BB84,
+		0x465D2303, 0x076C381A, 0xC43F1531, 0x850E0E28,
+		0x42984F67, 0x03A9547E, 0xC0FA7955, 0x81CB624C,
+		0x1FC53881, 0x5EF42398, 0x9DA70EB3, 0xDC9615AA,
+		0x1B0054E5, 0x5A314FFC, 0x996262D7, 0xD85379CE,
+		0x174FE149, 0x567EFA50, 0x952DD77B, 0xD41CCC62,
+		0x138A8D2D, 0x52BB9634, 0x91E8BB1F, 0xD0D9A006,
+		0xECF37E5E, 0xADC26547, 0x6E91486C, 0x2FA05375,
+		0xE836123A, 0xA9070923, 0x6A542408, 0x2B653F11,
+		0xE479A796, 0xA548BC8F, 0x661B91A4, 0x272A8ABD,
+		0xE0BCCBF2, 0xA18DD0EB, 0x62DEFDC0, 0x23EFE6D9,
+		0xBDE1BC14, 0xFCD0A70D, 0x3F838A26, 0x7EB2913F,
+		0xB924D070, 0xF815CB69, 0x3B46E642, 0x7A77FD5B,
+		0xB56B65DC, 0xF45A7EC5, 0x370953EE, 0x763848F7,
+		0xB1AE09B8, 0xF09F12A1, 0x33CC3F8A, 0x72FD2493
+	}, {
+		0x00000000, 0x376AC201, 0x6ED48403, 0x59BE4602,
+		0xDCA80907, 0xEBC2CB06, 0xB27C8D04, 0x85164F05,
+		0xB851130E, 0x8F3BD10F, 0xD685970D, 0xE1EF550C,
+		0x64F91A09, 0x5393D808, 0x0A2D9E0A, 0x3D475C0B,
+		0x70A3261C, 0x47C9E41D, 0x1E77A21F, 0x291D601E,
+		0xAC0B2F1B, 0x9B61ED1A, 0xC2DFAB18, 0xF5B56919,
+		0xC8F23512, 0xFF98F713, 0xA626B111, 0x914C7310,
+		0x145A3C15, 0x2330FE14, 0x7A8EB816, 0x4DE47A17,
+		0xE0464D38, 0xD72C8F39, 0x8E92C93B, 0xB9F80B3A,
+		0x3CEE443F, 0x0B84863E, 0x523AC03C, 0x6550023D,
+		0x58175E36, 0x6F7D9C37, 0x36C3DA35, 0x01A91834,
+		0x84BF5731, 0xB3D59530, 0xEA6BD332, 0xDD011133,
+		0x90E56B24, 0xA78FA925, 0xFE31EF27, 0xC95B2D26,
+		0x4C4D6223, 0x7B27A022, 0x2299E620, 0x15F32421,
+		0x28B4782A, 0x1FDEBA2B, 0x4660FC29, 0x710A3E28,
+		0xF41C712D, 0xC376B32C, 0x9AC8F52E, 0xADA2372F,
+		0xC08D9A70, 0xF7E75871, 0xAE591E73, 0x9933DC72,
+		0x1C259377, 0x2B4F5176, 0x72F11774, 0x459BD575,
+		0x78DC897E, 0x4FB64B7F, 0x16080D7D, 0x2162CF7C,
+		0xA4748079, 0x931E4278, 0xCAA0047A, 0xFDCAC67B,
+		0xB02EBC6C, 0x87447E6D, 0xDEFA386F, 0xE990FA6E,
+		0x6C86B56B, 0x5BEC776A, 0x02523168, 0x3538F369,
+		0x087FAF62, 0x3F156D63, 0x66AB2B61, 0x51C1E960,
+		0xD4D7A665, 0xE3BD6464, 0xBA032266, 0x8D69E067,
+		0x20CBD748, 0x17A11549, 0x4E1F534B, 0x7975914A,
+		0xFC63DE4F, 0xCB091C4E, 0x92B75A4C, 0xA5DD984D,
+		0x989AC446, 0xAFF00647, 0xF64E4045, 0xC1248244,
+		0x4432CD41, 0x73580F40, 0x2AE64942, 0x1D8C8B43,
+		0x5068F154, 0x67023355, 0x3EBC7557, 0x09D6B756,
+		0x8CC0F853, 0xBBAA3A52, 0xE2147C50, 0xD57EBE51,
+		0xE839E25A, 0xDF53205B, 0x86ED6659, 0xB187A458,
+		0x3491EB5D, 0x03FB295C, 0x5A456F5E, 0x6D2FAD5F,
+		0x801B35E1, 0xB771F7E0, 0xEECFB1E2, 0xD9A573E3,
+		0x5CB33CE6, 0x6BD9FEE7, 0x3267B8E5, 0x050D7AE4,
+		0x384A26EF, 0x0F20E4EE, 0x569EA2EC, 0x61F460ED,
+		0xE4E22FE8, 0xD388EDE9, 0x8A36ABEB, 0xBD5C69EA,
+		0xF0B813FD, 0xC7D2D1FC, 0x9E6C97FE, 0xA90655FF,
+		0x2C101AFA, 0x1B7AD8FB, 0x42C49EF9, 0x75AE5CF8,
+		0x48E900F3, 0x7F83C2F2, 0x263D84F0, 0x115746F1,
+		0x944109F4, 0xA32BCBF5, 0xFA958DF7, 0xCDFF4FF6,
+		0x605D78D9, 0x5737BAD8, 0x0E89FCDA, 0x39E33EDB,
+		0xBCF571DE, 0x8B9FB3DF, 0xD221F5DD, 0xE54B37DC,
+		0xD80C6BD7, 0xEF66A9D6, 0xB6D8EFD4, 0x81B22DD5,
+		0x04A462D0, 0x33CEA0D1, 0x6A70E6D3, 0x5D1A24D2,
+		0x10FE5EC5, 0x27949CC4, 0x7E2ADAC6, 0x494018C7,
+		0xCC5657C2, 0xFB3C95C3, 0xA282D3C1, 0x95E811C0,
+		0xA8AF4DCB, 0x9FC58FCA, 0xC67BC9C8, 0xF1110BC9,
+		0x740744CC, 0x436D86CD, 0x1AD3C0CF, 0x2DB902CE,
+		0x4096AF91, 0x77FC6D90, 0x2E422B92, 0x1928E993,
+		0x9C3EA696, 0xAB546497, 0xF2EA2295, 0xC580E094,
+		0xF8C7BC9F, 0xCFAD7E9E, 0x9613389C, 0xA179FA9D,
+		0x246FB598, 0x13057799, 0x4ABB319B, 0x7DD1F39A,
+		0x3035898D, 0x075F4B8C, 0x5EE10D8E, 0x698BCF8F,
+		0xEC9D808A, 0xDBF7428B, 0x82490489, 0xB523C688,
+		0x88649A83, 0xBF0E5882, 0xE6B01E80, 0xD1DADC81,
+		0x54CC9384, 0x63A65185, 0x3A181787, 0x0D72D586,
+		0xA0D0E2A9, 0x97BA20A8, 0xCE0466AA, 0xF96EA4AB,
+		0x7C78EBAE, 0x4B1229AF, 0x12AC6FAD, 0x25C6ADAC,
+		0x1881F1A7, 0x2FEB33A6, 0x765575A4, 0x413FB7A5,
+		0xC429F8A0, 0xF3433AA1, 0xAAFD7CA3, 0x9D97BEA2,
+		0xD073C4B5, 0xE71906B4, 0xBEA740B6, 0x89CD82B7,
+		0x0CDBCDB2, 0x3BB10FB3, 0x620F49B1, 0x55658BB0,
+		0x6822D7BB, 0x5F4815BA, 0x06F653B8, 0x319C91B9,
+		0xB48ADEBC, 0x83E01CBD, 0xDA5E5ABF, 0xED3498BE
+	}, {
+		0x00000000, 0x6567BCB8, 0x8BC809AA, 0xEEAFB512,
+		0x5797628F, 0x32F0DE37, 0xDC5F6B25, 0xB938D79D,
+		0xEF28B4C5, 0x8A4F087D, 0x64E0BD6F, 0x018701D7,
+		0xB8BFD64A, 0xDDD86AF2, 0x3377DFE0, 0x56106358,
+		0x9F571950, 0xFA30A5E8, 0x149F10FA, 0x71F8AC42,
+		0xC8C07BDF, 0xADA7C767, 0x43087275, 0x266FCECD,
+		0x707FAD95, 0x1518112D, 0xFBB7A43F, 0x9ED01887,
+		0x27E8CF1A, 0x428F73A2, 0xAC20C6B0, 0xC9477A08,
+		0x3EAF32A0, 0x5BC88E18, 0xB5673B0A, 0xD00087B2,
+		0x6938502F, 0x0C5FEC97, 0xE2F05985, 0x8797E53D,
+		0xD1878665, 0xB4E03ADD, 0x5A4F8FCF, 0x3F283377,
+		0x8610E4EA, 0xE3775852, 0x0DD8ED40, 0x68BF51F8,
+		0xA1F82BF0, 0xC49F9748, 0x2A30225A, 0x4F579EE2,
+		0xF66F497F, 0x9308F5C7, 0x7DA740D5, 0x18C0FC6D,
+		0x4ED09F35, 0x2BB7238D, 0xC518969F, 0xA07F2A27,
+		0x1947FDBA, 0x7C204102, 0x928FF410, 0xF7E848A8,
+		0x3D58149B, 0x583FA823, 0xB6901D31, 0xD3F7A189,
+		0x6ACF7614, 0x0FA8CAAC, 0xE1077FBE, 0x8460C306,
+		0xD270A05E, 0xB7171CE6, 0x59B8A9F4, 0x3CDF154C,
+		0x85E7C2D1, 0xE0807E69, 0x0E2FCB7B, 0x6B4877C3,
+		0xA20F0DCB, 0xC768B173, 0x29C70461, 0x4CA0B8D9,
+		0xF5986F44, 0x90FFD3FC, 0x7E5066EE, 0x1B37DA56,
+		0x4D27B90E, 0x284005B6, 0xC6EFB0A4, 0xA3880C1C,
+		0x1AB0DB81, 0x7FD76739, 0x9178D22B, 0xF41F6E93,
+		0x03F7263B, 0x66909A83, 0x883F2F91, 0xED589329,
+		0x546044B4, 0x3107F80C, 0xDFA84D1E, 0xBACFF1A6,
+		0xECDF92FE, 0x89B82E46, 0x67179B54, 0x027027EC,
+		0xBB48F071, 0xDE2F4CC9, 0x3080F9DB, 0x55E74563,
+		0x9CA03F6B, 0xF9C783D3, 0x176836C1, 0x720F8A79,
+		0xCB375DE4, 0xAE50E15C, 0x40FF544E, 0x2598E8F6,
+		0x73888BAE, 0x16EF3716, 0xF8408204, 0x9D273EBC,
+		0x241FE921, 0x41785599, 0xAFD7E08B, 0xCAB05C33,
+		0x3BB659ED, 0x5ED1E555, 0xB07E5047, 0xD519ECFF,
+		0x6C213B62, 0x094687DA, 0xE7E932C8, 0x828E8E70,
+		0xD49EED28, 0xB1F95190, 0x5F56E482, 0x3A31583A,
+		0x83098FA7, 0xE66E331F, 0x08C1860D, 0x6DA63AB5,
+		0xA4E140BD, 0xC186FC05, 0x2F294917, 0x4A4EF5AF,
+		0xF3762232, 0x96119E8A, 0x78BE2B98, 0x1DD99720,
+		0x4BC9F478, 0x2EAE48C0, 0xC001FDD2, 0xA566416A,
+		0x1C5E96F7, 0x79392A4F, 0x97969F5D, 0xF2F123E5,
+		0x05196B4D, 0x607ED7F5, 0x8ED162E7, 0xEBB6DE5F,
+		0x528E09C2, 0x37E9B57A, 0xD9460068, 0xBC21BCD0,
+		0xEA31DF88, 0x8F566330, 0x61F9D622, 0x049E6A9A,
+		0xBDA6BD07, 0xD8C101BF, 0x366EB4AD, 0x53090815,
+		0x9A4E721D, 0xFF29CEA5, 0x11867BB7, 0x74E1C70F,
+		0xCDD91092, 0xA8BEAC2A, 0x46111938, 0x2376A580,
+		0x7566C6D8, 0x10017A60, 0xFEAECF72, 0x9BC973CA,
+		0x22F1A457, 0x479618EF, 0xA939ADFD, 0xCC5E1145,
+		0x06EE4D76, 0x6389F1CE, 0x8D2644DC, 0xE841F864,
+		0x51792FF9, 0x341E9341, 0xDAB12653, 0xBFD69AEB,
+		0xE9C6F9B3, 0x8CA1450B, 0x620EF019, 0x07694CA1,
+		0xBE519B3C, 0xDB362784, 0x35999296, 0x50FE2E2E,
+		0x99B95426, 0xFCDEE89E, 0x12715D8C, 0x7716E134,
+		0xCE2E36A9, 0xAB498A11, 0x45E63F03, 0x208183BB,
+		0x7691E0E3, 0x13F65C5B, 0xFD59E949, 0x983E55F1,
+		0x2106826C, 0x44613ED4, 0xAACE8BC6, 0xCFA9377E,
+		0x38417FD6, 0x5D26C36E, 0xB389767C, 0xD6EECAC4,
+		0x6FD61D59, 0x0AB1A1E1, 0xE41E14F3, 0x8179A84B,
+		0xD769CB13, 0xB20E77AB, 0x5CA1C2B9, 0x39C67E01,
+		0x80FEA99C, 0xE5991524, 0x0B36A036, 0x6E511C8E,
+		0xA7166686, 0xC271DA3E, 0x2CDE6F2C, 0x49B9D394,
+		0xF0810409, 0x95E6B8B1, 0x7B490DA3, 0x1E2EB11B,
+		0x483ED243, 0x2D596EFB, 0xC3F6DBE9, 0xA6916751,
+		0x1FA9B0CC, 0x7ACE0C74, 0x9461B966, 0xF10605DE
+	}, {
+		0x00000000, 0xB029603D, 0x6053C07A, 0xD07AA047,
+		0xC0A680F5, 0x708FE0C8, 0xA0F5408F, 0x10DC20B2,
+		0xC14B7030, 0x7162100D, 0xA118B04A, 0x1131D077,
+		0x01EDF0C5, 0xB1C490F8, 0x61BE30BF, 0xD1975082,
+		0x8297E060, 0x32BE805D, 0xE2C4201A, 0x52ED4027,
+		0x42316095, 0xF21800A8, 0x2262A0EF, 0x924BC0D2,
+		0x43DC9050, 0xF3F5F06D, 0x238F502A, 0x93A63017,
+		0x837A10A5, 0x33537098, 0xE329D0DF, 0x5300B0E2,
+		0x042FC1C1, 0xB406A1FC, 0x647C01BB, 0xD4556186,
+		0xC4894134, 0x74A02109, 0xA4DA814E, 0x14F3E173,
+		0xC564B1F1, 0x754DD1CC, 0xA537718B, 0x151E11B6,
+		0x05C23104, 0xB5EB5139, 0x6591F17E, 0xD5B89143,
+		0x86B821A1, 0x3691419C, 0xE6EBE1DB, 0x56C281E6,
+		0x461EA154, 0xF637C169, 0x264D612E, 0x96640113,
+		0x47F35191, 0xF7DA31AC, 0x27A091EB, 0x9789F1D6,
+		0x8755D164, 0x377CB159, 0xE706111E, 0x572F7123,
+		0x4958F358, 0xF9719365, 0x290B3322, 0x9922531F,
+		0x89FE73AD, 0x39D71390, 0xE9ADB3D7, 0x5984D3EA,
+		0x88138368, 0x383AE355, 0xE8404312, 0x5869232F,
+		0x48B5039D, 0xF89C63A0, 0x28E6C3E7, 0x98CFA3DA,
+		0xCBCF1338, 0x7BE67305, 0xAB9CD342, 0x1BB5B37F,
+		0x0B6993CD, 0xBB40F3F0, 0x6B3A53B7, 0xDB13338A,
+		0x0A846308, 0xBAAD0335, 0x6AD7A372, 0xDAFEC34F,
+		0xCA22E3FD, 0x7A0B83C0, 0xAA712387, 0x1A5843BA,
+		0x4D773299, 0xFD5E52A4, 0x2D24F2E3, 0x9D0D92DE,
+		0x8DD1B26C, 0x3DF8D251, 0xED827216, 0x5DAB122B,
+		0x8C3C42A9, 0x3C152294, 0xEC6F82D3, 0x5C46E2EE,
+		0x4C9AC25C, 0xFCB3A261, 0x2CC90226, 0x9CE0621B,
+		0xCFE0D2F9, 0x7FC9B2C4, 0xAFB31283, 0x1F9A72BE,
+		0x0F46520C, 0xBF6F3231, 0x6F159276, 0xDF3CF24B,
+		0x0EABA2C9, 0xBE82C2F4, 0x6EF862B3, 0xDED1028E,
+		0xCE0D223C, 0x7E244201, 0xAE5EE246, 0x1E77827B,
+		0x92B0E6B1, 0x2299868C, 0xF2E326CB, 0x42CA46F6,
+		0x52166644, 0xE23F0679, 0x3245A63E, 0x826CC603,
+		0x53FB9681, 0xE3D2F6BC, 0x33A856FB, 0x838136C6,
+		0x935D1674, 0x23747649, 0xF30ED60E, 0x4327B633,
+		0x102706D1, 0xA00E66EC, 0x7074C6AB, 0xC05DA696,
+		0xD0818624, 0x60A8E619, 0xB0D2465E, 0x00FB2663,
+		0xD16C76E1, 0x614516DC, 0xB13FB69B, 0x0116D6A6,
+		0x11CAF614, 0xA1E39629, 0x7199366E, 0xC1B05653,
+		0x969F2770, 0x26B6474D, 0xF6CCE70A, 0x46E58737,
+		0x5639A785, 0xE610C7B8, 0x366A67FF, 0x864307C2,
+		0x57D45740, 0xE7FD377D, 0x3787973A, 0x87AEF707,
+		0x9772D7B5, 0x275BB788, 0xF72117CF, 0x470877F2,
+		0x1408C710, 0xA421A72D, 0x745B076A, 0xC4726757,
+		0xD4AE47E5, 0x648727D8, 0xB4FD879F, 0x04D4E7A2,
+		0xD543B720, 0x656AD71D, 0xB510775A, 0x05391767,
+		0x15E537D5, 0xA5CC57E8, 0x75B6F7AF, 0xC59F9792,
+		0xDBE815E9, 0x6BC175D4, 0xBBBBD593, 0x0B92B5AE,
+		0x1B4E951C, 0xAB67F521, 0x7B1D5566, 0xCB34355B,
+		0x1AA365D9, 0xAA8A05E4, 0x7AF0A5A3, 0xCAD9C59E,
+		0xDA05E52C, 0x6A2C8511, 0xBA562556, 0x0A7F456B,
+		0x597FF589, 0xE95695B4, 0x392C35F3, 0x890555CE,
+		0x99D9757C, 0x29F01541, 0xF98AB506, 0x49A3D53B,
+		0x983485B9, 0x281DE584, 0xF86745C3, 0x484E25FE,
+		0x5892054C, 0xE8BB6571, 0x38C1C536, 0x88E8A50B,
+		0xDFC7D428, 0x6FEEB415, 0xBF941452, 0x0FBD746F,
+		0x1F6154DD, 0xAF4834E0, 0x7F3294A7, 0xCF1BF49A,
+		0x1E8CA418, 0xAEA5C425, 0x7EDF6462, 0xCEF6045F,
+		0xDE2A24ED, 0x6E0344D0, 0xBE79E497, 0x0E5084AA,
+		0x5D503448, 0xED795475, 0x3D03F432, 0x8D2A940F,
+		0x9DF6B4BD, 0x2DDFD480, 0xFDA574C7, 0x4D8C14FA,
+		0x9C1B4478, 0x2C322445, 0xFC488402, 0x4C61E43F,
+		0x5CBDC48D, 0xEC94A4B0, 0x3CEE04F7, 0x8CC764CA
+	}, {
+		0x00000000, 0xA5D35CCB, 0x0BA1C84D, 0xAE729486,
+		0x1642919B, 0xB391CD50, 0x1DE359D6, 0xB830051D,
+		0x6D8253EC, 0xC8510F27, 0x66239BA1, 0xC3F0C76A,
+		0x7BC0C277, 0xDE139EBC, 0x70610A3A, 0xD5B256F1,
+		0x9B02D603, 0x3ED18AC8, 0x90A31E4E, 0x35704285,
+		0x8D404798, 0x28931B53, 0x86E18FD5, 0x2332D31E,
+		0xF68085EF, 0x5353D924, 0xFD214DA2, 0x58F21169,
+		0xE0C21474, 0x451148BF, 0xEB63DC39, 0x4EB080F2,
+		0x3605AC07, 0x93D6F0CC, 0x3DA4644A, 0x98773881,
+		0x20473D9C, 0x85946157, 0x2BE6F5D1, 0x8E35A91A,
+		0x5B87FFEB, 0xFE54A320, 0x502637A6, 0xF5F56B6D,
+		0x4DC56E70, 0xE81632BB, 0x4664A63D, 0xE3B7FAF6,
+		0xAD077A04, 0x08D426CF, 0xA6A6B249, 0x0375EE82,
+		0xBB45EB9F, 0x1E96B754, 0xB0E423D2, 0x15377F19,
+		0xC08529E8, 0x65567523, 0xCB24E1A5, 0x6EF7BD6E,
+		0xD6C7B873, 0x7314E4B8, 0xDD66703E, 0x78B52CF5,
+		0x6C0A580F, 0xC9D904C4, 0x67AB9042, 0xC278CC89,
+		0x7A48C994, 0xDF9B955F, 0x71E901D9, 0xD43A5D12,
+		0x01880BE3, 0xA45B5728, 0x0A29C3AE, 0xAFFA9F65,
+		0x17CA9A78, 0xB219C6B3, 0x1C6B5235, 0xB9B80EFE,
+		0xF7088E0C, 0x52DBD2C7, 0xFCA94641, 0x597A1A8A,
+		0xE14A1F97, 0x4499435C, 0xEAEBD7DA, 0x4F388B11,
+		0x9A8ADDE0, 0x3F59812B, 0x912B15AD, 0x34F84966,
+		0x8CC84C7B, 0x291B10B0, 0x87698436, 0x22BAD8FD,
+		0x5A0FF408, 0xFFDCA8C3, 0x51AE3C45, 0xF47D608E,
+		0x4C4D6593, 0xE99E3958, 0x47ECADDE, 0xE23FF115,
+		0x378DA7E4, 0x925EFB2F, 0x3C2C6FA9, 0x99FF3362,
+		0x21CF367F, 0x841C6AB4, 0x2A6EFE32, 0x8FBDA2F9,
+		0xC10D220B, 0x64DE7EC0, 0xCAACEA46, 0x6F7FB68D,
+		0xD74FB390, 0x729CEF5B, 0xDCEE7BDD, 0x793D2716,
+		0xAC8F71E7, 0x095C2D2C, 0xA72EB9AA, 0x02FDE561,
+		0xBACDE07C, 0x1F1EBCB7, 0xB16C2831, 0x14BF74FA,
+		0xD814B01E, 0x7DC7ECD5, 0xD3B57853, 0x76662498,
+		0xCE562185, 0x6B857D4E, 0xC5F7E9C8, 0x6024B503,
+		0xB596E3F2, 0x1045BF39, 0xBE372BBF, 0x1BE47774,
+		0xA3D47269, 0x06072EA2, 0xA875BA24, 0x0DA6E6EF,
+		0x4316661D, 0xE6C53AD6, 0x48B7AE50, 0xED64F29B,
+		0x5554F786, 0xF087AB4D, 0x5EF53FCB, 0xFB266300,
+		0x2E9435F1, 0x8B47693A, 0x2535FDBC, 0x80E6A177,
+		0x38D6A46A, 0x9D05F8A1, 0x33776C27, 0x96A430EC,
+		0xEE111C19, 0x4BC240D2, 0xE5B0D454, 0x4063889F,
+		0xF8538D82, 0x5D80D149, 0xF3F245CF, 0x56211904,
+		0x83934FF5, 0x2640133E, 0x883287B8, 0x2DE1DB73,
+		0x95D1DE6E, 0x300282A5, 0x9E701623, 0x3BA34AE8,
+		0x7513CA1A, 0xD0C096D1, 0x7EB20257, 0xDB615E9C,
+		0x63515B81, 0xC682074A, 0x68F093CC, 0xCD23CF07,
+		0x189199F6, 0xBD42C53D, 0x133051BB, 0xB6E30D70,
+		0x0ED3086D, 0xAB0054A6, 0x0572C020, 0xA0A19CEB,
+		0xB41EE811, 0x11CDB4DA, 0xBFBF205C, 0x1A6C7C97,
+		0xA25C798A, 0x078F2541, 0xA9FDB1C7, 0x0C2EED0C,
+		0xD99CBBFD, 0x7C4FE736, 0xD23D73B0, 0x77EE2F7B,
+		0xCFDE2A66, 0x6A0D76AD, 0xC47FE22B, 0x61ACBEE0,
+		0x2F1C3E12, 0x8ACF62D9, 0x24BDF65F, 0x816EAA94,
+		0x395EAF89, 0x9C8DF342, 0x32FF67C4, 0x972C3B0F,
+		0x429E6DFE, 0xE74D3135, 0x493FA5B3, 0xECECF978,
+		0x54DCFC65, 0xF10FA0AE, 0x5F7D3428, 0xFAAE68E3,
+		0x821B4416, 0x27C818DD, 0x89BA8C5B, 0x2C69D090,
+		0x9459D58D, 0x318A8946, 0x9FF81DC0, 0x3A2B410B,
+		0xEF9917FA, 0x4A4A4B31, 0xE438DFB7, 0x41EB837C,
+		0xF9DB8661, 0x5C08DAAA, 0xF27A4E2C, 0x57A912E7,
+		0x19199215, 0xBCCACEDE, 0x12B85A58, 0xB76B0693,
+		0x0F5B038E, 0xAA885F45, 0x04FACBC3, 0xA1299708,
+		0x749BC1F9, 0xD1489D32, 0x7F3A09B4, 0xDAE9557F,
+		0x62D95062, 0xC70A0CA9, 0x6978982F, 0xCCABC4E4
+	}, {
+		0x00000000, 0xB40B77A6, 0x29119F97, 0x9D1AE831,
+		0x13244FF4, 0xA72F3852, 0x3A35D063, 0x8E3EA7C5,
+		0x674EEF33, 0xD3459895, 0x4E5F70A4, 0xFA540702,
+		0x746AA0C7, 0xC061D761, 0x5D7B3F50, 0xE97048F6,
+		0xCE9CDE67, 0x7A97A9C1, 0xE78D41F0, 0x53863656,
+		0xDDB89193, 0x69B3E635, 0xF4A90E04, 0x40A279A2,
+		0xA9D23154, 0x1DD946F2, 0x80C3AEC3, 0x34C8D965,
+		0xBAF67EA0, 0x0EFD0906, 0x93E7E137, 0x27EC9691,
+		0x9C39BDCF, 0x2832CA69, 0xB5282258, 0x012355FE,
+		0x8F1DF23B, 0x3B16859D, 0xA60C6DAC, 0x12071A0A,
+		0xFB7752FC, 0x4F7C255A, 0xD266CD6B, 0x666DBACD,
+		0xE8531D08, 0x5C586AAE, 0xC142829F, 0x7549F539,
+		0x52A563A8, 0xE6AE140E, 0x7BB4FC3F, 0xCFBF8B99,
+		0x41812C5C, 0xF58A5BFA, 0x6890B3CB, 0xDC9BC46D,
+		0x35EB8C9B, 0x81E0FB3D, 0x1CFA130C, 0xA8F164AA,
+		0x26CFC36F, 0x92C4B4C9, 0x0FDE5CF8, 0xBBD52B5E,
+		0x79750B44, 0xCD7E7CE2, 0x506494D3, 0xE46FE375,
+		0x6A5144B0, 0xDE5A3316, 0x4340DB27, 0xF74BAC81,
+		0x1E3BE477, 0xAA3093D1, 0x372A7BE0, 0x83210C46,
+		0x0D1FAB83, 0xB914DC25, 0x240E3414, 0x900543B2,
+		0xB7E9D523, 0x03E2A285, 0x9EF84AB4, 0x2AF33D12,
+		0xA4CD9AD7, 0x10C6ED71, 0x8DDC0540, 0x39D772E6,
+		0xD0A73A10, 0x64AC4DB6, 0xF9B6A587, 0x4DBDD221,
+		0xC38375E4, 0x77880242, 0xEA92EA73, 0x5E999DD5,
+		0xE54CB68B, 0x5147C12D, 0xCC5D291C, 0x78565EBA,
+		0xF668F97F, 0x42638ED9, 0xDF7966E8, 0x6B72114E,
+		0x820259B8, 0x36092E1E, 0xAB13C62F, 0x1F18B189,
+		0x9126164C, 0x252D61EA, 0xB83789DB, 0x0C3CFE7D,
+		0x2BD068EC, 0x9FDB1F4A, 0x02C1F77B, 0xB6CA80DD,
+		0x38F42718, 0x8CFF50BE, 0x11E5B88F, 0xA5EECF29,
+		0x4C9E87DF, 0xF895F079, 0x658F1848, 0xD1846FEE,
+		0x5FBAC82B, 0xEBB1BF8D, 0x76AB57BC, 0xC2A0201A,
+		0xF2EA1688, 0x46E1612E, 0xDBFB891F, 0x6FF0FEB9,
+		0xE1CE597C, 0x55C52EDA, 0xC8DFC6EB, 0x7CD4B14D,
+		0x95A4F9BB, 0x21AF8E1D, 0xBCB5662C, 0x08BE118A,
+		0x8680B64F, 0x328BC1E9, 0xAF9129D8, 0x1B9A5E7E,
+		0x3C76C8EF, 0x887DBF49, 0x15675778, 0xA16C20DE,
+		0x2F52871B, 0x9B59F0BD, 0x0643188C, 0xB2486F2A,
+		0x5B3827DC, 0xEF33507A, 0x7229B84B, 0xC622CFED,
+		0x481C6828, 0xFC171F8E, 0x610DF7BF, 0xD5068019,
+		0x6ED3AB47, 0xDAD8DCE1, 0x47C234D0, 0xF3C94376,
+		0x7DF7E4B3, 0xC9FC9315, 0x54E67B24, 0xE0ED0C82,
+		0x099D4474, 0xBD9633D2, 0x208CDBE3, 0x9487AC45,
+		0x1AB90B80, 0xAEB27C26, 0x33A89417, 0x87A3E3B1,
+		0xA04F7520, 0x14440286, 0x895EEAB7, 0x3D559D11,
+		0xB36B3AD4, 0x07604D72, 0x9A7AA543, 0x2E71D2E5,
+		0xC7019A13, 0x730AEDB5, 0xEE100584, 0x5A1B7222,
+		0xD425D5E7, 0x602EA241, 0xFD344A70, 0x493F3DD6,
+		0x8B9F1DCC, 0x3F946A6A, 0xA28E825B, 0x1685F5FD,
+		0x98BB5238, 0x2CB0259E, 0xB1AACDAF, 0x05A1BA09,
+		0xECD1F2FF, 0x58DA8559, 0xC5C06D68, 0x71CB1ACE,
+		0xFFF5BD0B, 0x4BFECAAD, 0xD6E4229C, 0x62EF553A,
+		0x4503C3AB, 0xF108B40D, 0x6C125C3C, 0xD8192B9A,
+		0x56278C5F, 0xE22CFBF9, 0x7F3613C8, 0xCB3D646E,
+		0x224D2C98, 0x96465B3E, 0x0B5CB30F, 0xBF57C4A9,
+		0x3169636C, 0x856214CA, 0x1878FCFB, 0xAC738B5D,
+		0x17A6A003, 0xA3ADD7A5, 0x3EB73F94, 0x8ABC4832,
+		0x0482EFF7, 0xB0899851, 0x2D937060, 0x999807C6,
+		0x70E84F30, 0xC4E33896, 0x59F9D0A7, 0xEDF2A701,
+		0x63CC00C4, 0xD7C77762, 0x4ADD9F53, 0xFED6E8F5,
+		0xD93A7E64, 0x6D3109C2, 0xF02BE1F3, 0x44209655,
+		0xCA1E3190, 0x7E154636, 0xE30FAE07, 0x5704D9A1,
+		0xBE749157, 0x0A7FE6F1, 0x97650EC0, 0x236E7966,
+		0xAD50DEA3, 0x195BA905, 0x84414134, 0x304A3692
+	}, {
+		0x00000000, 0x9E00AACC, 0x7D072542, 0xE3078F8E,
+		0xFA0E4A84, 0x640EE048, 0x87096FC6, 0x1909C50A,
+		0xB51BE5D3, 0x2B1B4F1F, 0xC81CC091, 0x561C6A5D,
+		0x4F15AF57, 0xD115059B, 0x32128A15, 0xAC1220D9,
+		0x2B31BB7C, 0xB53111B0, 0x56369E3E, 0xC83634F2,
+		0xD13FF1F8, 0x4F3F5B34, 0xAC38D4BA, 0x32387E76,
+		0x9E2A5EAF, 0x002AF463, 0xE32D7BED, 0x7D2DD121,
+		0x6424142B, 0xFA24BEE7, 0x19233169, 0x87239BA5,
+		0x566276F9, 0xC862DC35, 0x2B6553BB, 0xB565F977,
+		0xAC6C3C7D, 0x326C96B1, 0xD16B193F, 0x4F6BB3F3,
+		0xE379932A, 0x7D7939E6, 0x9E7EB668, 0x007E1CA4,
+		0x1977D9AE, 0x87777362, 0x6470FCEC, 0xFA705620,
+		0x7D53CD85, 0xE3536749, 0x0054E8C7, 0x9E54420B,
+		0x875D8701, 0x195D2DCD, 0xFA5AA243, 0x645A088F,
+		0xC8482856, 0x5648829A, 0xB54F0D14, 0x2B4FA7D8,
+		0x324662D2, 0xAC46C81E, 0x4F414790, 0xD141ED5C,
+		0xEDC29D29, 0x73C237E5, 0x90C5B86B, 0x0EC512A7,
+		0x17CCD7AD, 0x89CC7D61, 0x6ACBF2EF, 0xF4CB5823,
+		0x58D978FA, 0xC6D9D236, 0x25DE5DB8, 0xBBDEF774,
+		0xA2D7327E, 0x3CD798B2, 0xDFD0173C, 0x41D0BDF0,
+		0xC6F32655, 0x58F38C99, 0xBBF40317, 0x25F4A9DB,
+		0x3CFD6CD1, 0xA2FDC61D, 0x41FA4993, 0xDFFAE35F,
+		0x73E8C386, 0xEDE8694A, 0x0EEFE6C4, 0x90EF4C08,
+		0x89E68902, 0x17E623CE, 0xF4E1AC40, 0x6AE1068C,
+		0xBBA0EBD0, 0x25A0411C, 0xC6A7CE92, 0x58A7645E,
+		0x41AEA154, 0xDFAE0B98, 0x3CA98416, 0xA2A92EDA,
+		0x0EBB0E03, 0x90BBA4CF, 0x73BC2B41, 0xEDBC818D,
+		0xF4B54487, 0x6AB5EE4B, 0x89B261C5, 0x17B2CB09,
+		0x909150AC, 0x0E91FA60, 0xED9675EE, 0x7396DF22,
+		0x6A9F1A28, 0xF49FB0E4, 0x17983F6A, 0x899895A6,
+		0x258AB57F, 0xBB8A1FB3, 0x588D903D, 0xC68D3AF1,
+		0xDF84FFFB, 0x41845537, 0xA283DAB9, 0x3C837075,
+		0xDA853B53, 0x4485919F, 0xA7821E11, 0x3982B4DD,
+		0x208B71D7, 0xBE8BDB1B, 0x5D8C5495, 0xC38CFE59,
+		0x6F9EDE80, 0xF19E744C, 0x1299FBC2, 0x8C99510E,
+		0x95909404, 0x0B903EC8, 0xE897B146, 0x76971B8A,
+		0xF1B4802F, 0x6FB42AE3, 0x8CB3A56D, 0x12B30FA1,
+		0x0BBACAAB, 0x95BA6067, 0x76BDEFE9, 0xE8BD4525,
+		0x44AF65FC, 0xDAAFCF30, 0x39A840BE, 0xA7A8EA72,
+		0xBEA12F78, 0x20A185B4, 0xC3A60A3A, 0x5DA6A0F6,
+		0x8CE74DAA, 0x12E7E766, 0xF1E068E8, 0x6FE0C224,
+		0x76E9072E, 0xE8E9ADE2, 0x0BEE226C, 0x95EE88A0,
+		0x39FCA879, 0xA7FC02B5, 0x44FB8D3B, 0xDAFB27F7,
+		0xC3F2E2FD, 0x5DF24831, 0xBEF5C7BF, 0x20F56D73,
+		0xA7D6F6D6, 0x39D65C1A, 0xDAD1D394, 0x44D17958,
+		0x5DD8BC52, 0xC3D8169E, 0x20DF9910, 0xBEDF33DC,
+		0x12CD1305, 0x8CCDB9C9, 0x6FCA3647, 0xF1CA9C8B,
+		0xE8C35981, 0x76C3F34D, 0x95C47CC3, 0x0BC4D60F,
+		0x3747A67A, 0xA9470CB6, 0x4A408338, 0xD44029F4,
+		0xCD49ECFE, 0x53494632, 0xB04EC9BC, 0x2E4E6370,
+		0x825C43A9, 0x1C5CE965, 0xFF5B66EB, 0x615BCC27,
+		0x7852092D, 0xE652A3E1, 0x05552C6F, 0x9B5586A3,
+		0x1C761D06, 0x8276B7CA, 0x61713844, 0xFF719288,
+		0xE6785782, 0x7878FD4E, 0x9B7F72C0, 0x057FD80C,
+		0xA96DF8D5, 0x376D5219, 0xD46ADD97, 0x4A6A775B,
+		0x5363B251, 0xCD63189D, 0x2E649713, 0xB0643DDF,
+		0x6125D083, 0xFF257A4F, 0x1C22F5C1, 0x82225F0D,
+		0x9B2B9A07, 0x052B30CB, 0xE62CBF45, 0x782C1589,
+		0xD43E3550, 0x4A3E9F9C, 0xA9391012, 0x3739BADE,
+		0x2E307FD4, 0xB030D518, 0x53375A96, 0xCD37F05A,
+		0x4A146BFF, 0xD414C133, 0x37134EBD, 0xA913E471,
+		0xB01A217B, 0x2E1A8BB7, 0xCD1D0439, 0x531DAEF5,
+		0xFF0F8E2C, 0x610F24E0, 0x8208AB6E, 0x1C0801A2,
+		0x0501C4A8, 0x9B016E64, 0x7806E1EA, 0xE6064B26
+	}
+};
diff --git a/Utilities/cmliblzma/liblzma/check/crc32_table_le.h b/Utilities/cmliblzma/liblzma/check/crc32_table_le.h
new file mode 100644
index 0000000..25f4fc4
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/check/crc32_table_le.h
@@ -0,0 +1,525 @@
+/* This file has been automatically generated by crc32_tablegen.c. */
+
+const uint32_t lzma_crc32_table[8][256] = {
+	{
+		0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA,
+		0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3,
+		0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988,
+		0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91,
+		0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE,
+		0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7,
+		0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC,
+		0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5,
+		0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172,
+		0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
+		0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940,
+		0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,
+		0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116,
+		0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F,
+		0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,
+		0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D,
+		0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A,
+		0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433,
+		0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818,
+		0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
+		0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E,
+		0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457,
+		0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C,
+		0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65,
+		0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2,
+		0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB,
+		0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0,
+		0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9,
+		0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086,
+		0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
+		0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4,
+		0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD,
+		0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A,
+		0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683,
+		0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8,
+		0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,
+		0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE,
+		0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7,
+		0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC,
+		0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,
+		0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252,
+		0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,
+		0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60,
+		0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79,
+		0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,
+		0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F,
+		0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04,
+		0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D,
+		0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A,
+		0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,
+		0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38,
+		0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21,
+		0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E,
+		0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777,
+		0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C,
+		0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45,
+		0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2,
+		0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB,
+		0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0,
+		0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
+		0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6,
+		0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF,
+		0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94,
+		0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D
+	}, {
+		0x00000000, 0x191B3141, 0x32366282, 0x2B2D53C3,
+		0x646CC504, 0x7D77F445, 0x565AA786, 0x4F4196C7,
+		0xC8D98A08, 0xD1C2BB49, 0xFAEFE88A, 0xE3F4D9CB,
+		0xACB54F0C, 0xB5AE7E4D, 0x9E832D8E, 0x87981CCF,
+		0x4AC21251, 0x53D92310, 0x78F470D3, 0x61EF4192,
+		0x2EAED755, 0x37B5E614, 0x1C98B5D7, 0x05838496,
+		0x821B9859, 0x9B00A918, 0xB02DFADB, 0xA936CB9A,
+		0xE6775D5D, 0xFF6C6C1C, 0xD4413FDF, 0xCD5A0E9E,
+		0x958424A2, 0x8C9F15E3, 0xA7B24620, 0xBEA97761,
+		0xF1E8E1A6, 0xE8F3D0E7, 0xC3DE8324, 0xDAC5B265,
+		0x5D5DAEAA, 0x44469FEB, 0x6F6BCC28, 0x7670FD69,
+		0x39316BAE, 0x202A5AEF, 0x0B07092C, 0x121C386D,
+		0xDF4636F3, 0xC65D07B2, 0xED705471, 0xF46B6530,
+		0xBB2AF3F7, 0xA231C2B6, 0x891C9175, 0x9007A034,
+		0x179FBCFB, 0x0E848DBA, 0x25A9DE79, 0x3CB2EF38,
+		0x73F379FF, 0x6AE848BE, 0x41C51B7D, 0x58DE2A3C,
+		0xF0794F05, 0xE9627E44, 0xC24F2D87, 0xDB541CC6,
+		0x94158A01, 0x8D0EBB40, 0xA623E883, 0xBF38D9C2,
+		0x38A0C50D, 0x21BBF44C, 0x0A96A78F, 0x138D96CE,
+		0x5CCC0009, 0x45D73148, 0x6EFA628B, 0x77E153CA,
+		0xBABB5D54, 0xA3A06C15, 0x888D3FD6, 0x91960E97,
+		0xDED79850, 0xC7CCA911, 0xECE1FAD2, 0xF5FACB93,
+		0x7262D75C, 0x6B79E61D, 0x4054B5DE, 0x594F849F,
+		0x160E1258, 0x0F152319, 0x243870DA, 0x3D23419B,
+		0x65FD6BA7, 0x7CE65AE6, 0x57CB0925, 0x4ED03864,
+		0x0191AEA3, 0x188A9FE2, 0x33A7CC21, 0x2ABCFD60,
+		0xAD24E1AF, 0xB43FD0EE, 0x9F12832D, 0x8609B26C,
+		0xC94824AB, 0xD05315EA, 0xFB7E4629, 0xE2657768,
+		0x2F3F79F6, 0x362448B7, 0x1D091B74, 0x04122A35,
+		0x4B53BCF2, 0x52488DB3, 0x7965DE70, 0x607EEF31,
+		0xE7E6F3FE, 0xFEFDC2BF, 0xD5D0917C, 0xCCCBA03D,
+		0x838A36FA, 0x9A9107BB, 0xB1BC5478, 0xA8A76539,
+		0x3B83984B, 0x2298A90A, 0x09B5FAC9, 0x10AECB88,
+		0x5FEF5D4F, 0x46F46C0E, 0x6DD93FCD, 0x74C20E8C,
+		0xF35A1243, 0xEA412302, 0xC16C70C1, 0xD8774180,
+		0x9736D747, 0x8E2DE606, 0xA500B5C5, 0xBC1B8484,
+		0x71418A1A, 0x685ABB5B, 0x4377E898, 0x5A6CD9D9,
+		0x152D4F1E, 0x0C367E5F, 0x271B2D9C, 0x3E001CDD,
+		0xB9980012, 0xA0833153, 0x8BAE6290, 0x92B553D1,
+		0xDDF4C516, 0xC4EFF457, 0xEFC2A794, 0xF6D996D5,
+		0xAE07BCE9, 0xB71C8DA8, 0x9C31DE6B, 0x852AEF2A,
+		0xCA6B79ED, 0xD37048AC, 0xF85D1B6F, 0xE1462A2E,
+		0x66DE36E1, 0x7FC507A0, 0x54E85463, 0x4DF36522,
+		0x02B2F3E5, 0x1BA9C2A4, 0x30849167, 0x299FA026,
+		0xE4C5AEB8, 0xFDDE9FF9, 0xD6F3CC3A, 0xCFE8FD7B,
+		0x80A96BBC, 0x99B25AFD, 0xB29F093E, 0xAB84387F,
+		0x2C1C24B0, 0x350715F1, 0x1E2A4632, 0x07317773,
+		0x4870E1B4, 0x516BD0F5, 0x7A468336, 0x635DB277,
+		0xCBFAD74E, 0xD2E1E60F, 0xF9CCB5CC, 0xE0D7848D,
+		0xAF96124A, 0xB68D230B, 0x9DA070C8, 0x84BB4189,
+		0x03235D46, 0x1A386C07, 0x31153FC4, 0x280E0E85,
+		0x674F9842, 0x7E54A903, 0x5579FAC0, 0x4C62CB81,
+		0x8138C51F, 0x9823F45E, 0xB30EA79D, 0xAA1596DC,
+		0xE554001B, 0xFC4F315A, 0xD7626299, 0xCE7953D8,
+		0x49E14F17, 0x50FA7E56, 0x7BD72D95, 0x62CC1CD4,
+		0x2D8D8A13, 0x3496BB52, 0x1FBBE891, 0x06A0D9D0,
+		0x5E7EF3EC, 0x4765C2AD, 0x6C48916E, 0x7553A02F,
+		0x3A1236E8, 0x230907A9, 0x0824546A, 0x113F652B,
+		0x96A779E4, 0x8FBC48A5, 0xA4911B66, 0xBD8A2A27,
+		0xF2CBBCE0, 0xEBD08DA1, 0xC0FDDE62, 0xD9E6EF23,
+		0x14BCE1BD, 0x0DA7D0FC, 0x268A833F, 0x3F91B27E,
+		0x70D024B9, 0x69CB15F8, 0x42E6463B, 0x5BFD777A,
+		0xDC656BB5, 0xC57E5AF4, 0xEE530937, 0xF7483876,
+		0xB809AEB1, 0xA1129FF0, 0x8A3FCC33, 0x9324FD72
+	}, {
+		0x00000000, 0x01C26A37, 0x0384D46E, 0x0246BE59,
+		0x0709A8DC, 0x06CBC2EB, 0x048D7CB2, 0x054F1685,
+		0x0E1351B8, 0x0FD13B8F, 0x0D9785D6, 0x0C55EFE1,
+		0x091AF964, 0x08D89353, 0x0A9E2D0A, 0x0B5C473D,
+		0x1C26A370, 0x1DE4C947, 0x1FA2771E, 0x1E601D29,
+		0x1B2F0BAC, 0x1AED619B, 0x18ABDFC2, 0x1969B5F5,
+		0x1235F2C8, 0x13F798FF, 0x11B126A6, 0x10734C91,
+		0x153C5A14, 0x14FE3023, 0x16B88E7A, 0x177AE44D,
+		0x384D46E0, 0x398F2CD7, 0x3BC9928E, 0x3A0BF8B9,
+		0x3F44EE3C, 0x3E86840B, 0x3CC03A52, 0x3D025065,
+		0x365E1758, 0x379C7D6F, 0x35DAC336, 0x3418A901,
+		0x3157BF84, 0x3095D5B3, 0x32D36BEA, 0x331101DD,
+		0x246BE590, 0x25A98FA7, 0x27EF31FE, 0x262D5BC9,
+		0x23624D4C, 0x22A0277B, 0x20E69922, 0x2124F315,
+		0x2A78B428, 0x2BBADE1F, 0x29FC6046, 0x283E0A71,
+		0x2D711CF4, 0x2CB376C3, 0x2EF5C89A, 0x2F37A2AD,
+		0x709A8DC0, 0x7158E7F7, 0x731E59AE, 0x72DC3399,
+		0x7793251C, 0x76514F2B, 0x7417F172, 0x75D59B45,
+		0x7E89DC78, 0x7F4BB64F, 0x7D0D0816, 0x7CCF6221,
+		0x798074A4, 0x78421E93, 0x7A04A0CA, 0x7BC6CAFD,
+		0x6CBC2EB0, 0x6D7E4487, 0x6F38FADE, 0x6EFA90E9,
+		0x6BB5866C, 0x6A77EC5B, 0x68315202, 0x69F33835,
+		0x62AF7F08, 0x636D153F, 0x612BAB66, 0x60E9C151,
+		0x65A6D7D4, 0x6464BDE3, 0x662203BA, 0x67E0698D,
+		0x48D7CB20, 0x4915A117, 0x4B531F4E, 0x4A917579,
+		0x4FDE63FC, 0x4E1C09CB, 0x4C5AB792, 0x4D98DDA5,
+		0x46C49A98, 0x4706F0AF, 0x45404EF6, 0x448224C1,
+		0x41CD3244, 0x400F5873, 0x4249E62A, 0x438B8C1D,
+		0x54F16850, 0x55330267, 0x5775BC3E, 0x56B7D609,
+		0x53F8C08C, 0x523AAABB, 0x507C14E2, 0x51BE7ED5,
+		0x5AE239E8, 0x5B2053DF, 0x5966ED86, 0x58A487B1,
+		0x5DEB9134, 0x5C29FB03, 0x5E6F455A, 0x5FAD2F6D,
+		0xE1351B80, 0xE0F771B7, 0xE2B1CFEE, 0xE373A5D9,
+		0xE63CB35C, 0xE7FED96B, 0xE5B86732, 0xE47A0D05,
+		0xEF264A38, 0xEEE4200F, 0xECA29E56, 0xED60F461,
+		0xE82FE2E4, 0xE9ED88D3, 0xEBAB368A, 0xEA695CBD,
+		0xFD13B8F0, 0xFCD1D2C7, 0xFE976C9E, 0xFF5506A9,
+		0xFA1A102C, 0xFBD87A1B, 0xF99EC442, 0xF85CAE75,
+		0xF300E948, 0xF2C2837F, 0xF0843D26, 0xF1465711,
+		0xF4094194, 0xF5CB2BA3, 0xF78D95FA, 0xF64FFFCD,
+		0xD9785D60, 0xD8BA3757, 0xDAFC890E, 0xDB3EE339,
+		0xDE71F5BC, 0xDFB39F8B, 0xDDF521D2, 0xDC374BE5,
+		0xD76B0CD8, 0xD6A966EF, 0xD4EFD8B6, 0xD52DB281,
+		0xD062A404, 0xD1A0CE33, 0xD3E6706A, 0xD2241A5D,
+		0xC55EFE10, 0xC49C9427, 0xC6DA2A7E, 0xC7184049,
+		0xC25756CC, 0xC3953CFB, 0xC1D382A2, 0xC011E895,
+		0xCB4DAFA8, 0xCA8FC59F, 0xC8C97BC6, 0xC90B11F1,
+		0xCC440774, 0xCD866D43, 0xCFC0D31A, 0xCE02B92D,
+		0x91AF9640, 0x906DFC77, 0x922B422E, 0x93E92819,
+		0x96A63E9C, 0x976454AB, 0x9522EAF2, 0x94E080C5,
+		0x9FBCC7F8, 0x9E7EADCF, 0x9C381396, 0x9DFA79A1,
+		0x98B56F24, 0x99770513, 0x9B31BB4A, 0x9AF3D17D,
+		0x8D893530, 0x8C4B5F07, 0x8E0DE15E, 0x8FCF8B69,
+		0x8A809DEC, 0x8B42F7DB, 0x89044982, 0x88C623B5,
+		0x839A6488, 0x82580EBF, 0x801EB0E6, 0x81DCDAD1,
+		0x8493CC54, 0x8551A663, 0x8717183A, 0x86D5720D,
+		0xA9E2D0A0, 0xA820BA97, 0xAA6604CE, 0xABA46EF9,
+		0xAEEB787C, 0xAF29124B, 0xAD6FAC12, 0xACADC625,
+		0xA7F18118, 0xA633EB2F, 0xA4755576, 0xA5B73F41,
+		0xA0F829C4, 0xA13A43F3, 0xA37CFDAA, 0xA2BE979D,
+		0xB5C473D0, 0xB40619E7, 0xB640A7BE, 0xB782CD89,
+		0xB2CDDB0C, 0xB30FB13B, 0xB1490F62, 0xB08B6555,
+		0xBBD72268, 0xBA15485F, 0xB853F606, 0xB9919C31,
+		0xBCDE8AB4, 0xBD1CE083, 0xBF5A5EDA, 0xBE9834ED
+	}, {
+		0x00000000, 0xB8BC6765, 0xAA09C88B, 0x12B5AFEE,
+		0x8F629757, 0x37DEF032, 0x256B5FDC, 0x9DD738B9,
+		0xC5B428EF, 0x7D084F8A, 0x6FBDE064, 0xD7018701,
+		0x4AD6BFB8, 0xF26AD8DD, 0xE0DF7733, 0x58631056,
+		0x5019579F, 0xE8A530FA, 0xFA109F14, 0x42ACF871,
+		0xDF7BC0C8, 0x67C7A7AD, 0x75720843, 0xCDCE6F26,
+		0x95AD7F70, 0x2D111815, 0x3FA4B7FB, 0x8718D09E,
+		0x1ACFE827, 0xA2738F42, 0xB0C620AC, 0x087A47C9,
+		0xA032AF3E, 0x188EC85B, 0x0A3B67B5, 0xB28700D0,
+		0x2F503869, 0x97EC5F0C, 0x8559F0E2, 0x3DE59787,
+		0x658687D1, 0xDD3AE0B4, 0xCF8F4F5A, 0x7733283F,
+		0xEAE41086, 0x525877E3, 0x40EDD80D, 0xF851BF68,
+		0xF02BF8A1, 0x48979FC4, 0x5A22302A, 0xE29E574F,
+		0x7F496FF6, 0xC7F50893, 0xD540A77D, 0x6DFCC018,
+		0x359FD04E, 0x8D23B72B, 0x9F9618C5, 0x272A7FA0,
+		0xBAFD4719, 0x0241207C, 0x10F48F92, 0xA848E8F7,
+		0x9B14583D, 0x23A83F58, 0x311D90B6, 0x89A1F7D3,
+		0x1476CF6A, 0xACCAA80F, 0xBE7F07E1, 0x06C36084,
+		0x5EA070D2, 0xE61C17B7, 0xF4A9B859, 0x4C15DF3C,
+		0xD1C2E785, 0x697E80E0, 0x7BCB2F0E, 0xC377486B,
+		0xCB0D0FA2, 0x73B168C7, 0x6104C729, 0xD9B8A04C,
+		0x446F98F5, 0xFCD3FF90, 0xEE66507E, 0x56DA371B,
+		0x0EB9274D, 0xB6054028, 0xA4B0EFC6, 0x1C0C88A3,
+		0x81DBB01A, 0x3967D77F, 0x2BD27891, 0x936E1FF4,
+		0x3B26F703, 0x839A9066, 0x912F3F88, 0x299358ED,
+		0xB4446054, 0x0CF80731, 0x1E4DA8DF, 0xA6F1CFBA,
+		0xFE92DFEC, 0x462EB889, 0x549B1767, 0xEC277002,
+		0x71F048BB, 0xC94C2FDE, 0xDBF98030, 0x6345E755,
+		0x6B3FA09C, 0xD383C7F9, 0xC1366817, 0x798A0F72,
+		0xE45D37CB, 0x5CE150AE, 0x4E54FF40, 0xF6E89825,
+		0xAE8B8873, 0x1637EF16, 0x048240F8, 0xBC3E279D,
+		0x21E91F24, 0x99557841, 0x8BE0D7AF, 0x335CB0CA,
+		0xED59B63B, 0x55E5D15E, 0x47507EB0, 0xFFEC19D5,
+		0x623B216C, 0xDA874609, 0xC832E9E7, 0x708E8E82,
+		0x28ED9ED4, 0x9051F9B1, 0x82E4565F, 0x3A58313A,
+		0xA78F0983, 0x1F336EE6, 0x0D86C108, 0xB53AA66D,
+		0xBD40E1A4, 0x05FC86C1, 0x1749292F, 0xAFF54E4A,
+		0x322276F3, 0x8A9E1196, 0x982BBE78, 0x2097D91D,
+		0x78F4C94B, 0xC048AE2E, 0xD2FD01C0, 0x6A4166A5,
+		0xF7965E1C, 0x4F2A3979, 0x5D9F9697, 0xE523F1F2,
+		0x4D6B1905, 0xF5D77E60, 0xE762D18E, 0x5FDEB6EB,
+		0xC2098E52, 0x7AB5E937, 0x680046D9, 0xD0BC21BC,
+		0x88DF31EA, 0x3063568F, 0x22D6F961, 0x9A6A9E04,
+		0x07BDA6BD, 0xBF01C1D8, 0xADB46E36, 0x15080953,
+		0x1D724E9A, 0xA5CE29FF, 0xB77B8611, 0x0FC7E174,
+		0x9210D9CD, 0x2AACBEA8, 0x38191146, 0x80A57623,
+		0xD8C66675, 0x607A0110, 0x72CFAEFE, 0xCA73C99B,
+		0x57A4F122, 0xEF189647, 0xFDAD39A9, 0x45115ECC,
+		0x764DEE06, 0xCEF18963, 0xDC44268D, 0x64F841E8,
+		0xF92F7951, 0x41931E34, 0x5326B1DA, 0xEB9AD6BF,
+		0xB3F9C6E9, 0x0B45A18C, 0x19F00E62, 0xA14C6907,
+		0x3C9B51BE, 0x842736DB, 0x96929935, 0x2E2EFE50,
+		0x2654B999, 0x9EE8DEFC, 0x8C5D7112, 0x34E11677,
+		0xA9362ECE, 0x118A49AB, 0x033FE645, 0xBB838120,
+		0xE3E09176, 0x5B5CF613, 0x49E959FD, 0xF1553E98,
+		0x6C820621, 0xD43E6144, 0xC68BCEAA, 0x7E37A9CF,
+		0xD67F4138, 0x6EC3265D, 0x7C7689B3, 0xC4CAEED6,
+		0x591DD66F, 0xE1A1B10A, 0xF3141EE4, 0x4BA87981,
+		0x13CB69D7, 0xAB770EB2, 0xB9C2A15C, 0x017EC639,
+		0x9CA9FE80, 0x241599E5, 0x36A0360B, 0x8E1C516E,
+		0x866616A7, 0x3EDA71C2, 0x2C6FDE2C, 0x94D3B949,
+		0x090481F0, 0xB1B8E695, 0xA30D497B, 0x1BB12E1E,
+		0x43D23E48, 0xFB6E592D, 0xE9DBF6C3, 0x516791A6,
+		0xCCB0A91F, 0x740CCE7A, 0x66B96194, 0xDE0506F1
+	}, {
+		0x00000000, 0x3D6029B0, 0x7AC05360, 0x47A07AD0,
+		0xF580A6C0, 0xC8E08F70, 0x8F40F5A0, 0xB220DC10,
+		0x30704BC1, 0x0D106271, 0x4AB018A1, 0x77D03111,
+		0xC5F0ED01, 0xF890C4B1, 0xBF30BE61, 0x825097D1,
+		0x60E09782, 0x5D80BE32, 0x1A20C4E2, 0x2740ED52,
+		0x95603142, 0xA80018F2, 0xEFA06222, 0xD2C04B92,
+		0x5090DC43, 0x6DF0F5F3, 0x2A508F23, 0x1730A693,
+		0xA5107A83, 0x98705333, 0xDFD029E3, 0xE2B00053,
+		0xC1C12F04, 0xFCA106B4, 0xBB017C64, 0x866155D4,
+		0x344189C4, 0x0921A074, 0x4E81DAA4, 0x73E1F314,
+		0xF1B164C5, 0xCCD14D75, 0x8B7137A5, 0xB6111E15,
+		0x0431C205, 0x3951EBB5, 0x7EF19165, 0x4391B8D5,
+		0xA121B886, 0x9C419136, 0xDBE1EBE6, 0xE681C256,
+		0x54A11E46, 0x69C137F6, 0x2E614D26, 0x13016496,
+		0x9151F347, 0xAC31DAF7, 0xEB91A027, 0xD6F18997,
+		0x64D15587, 0x59B17C37, 0x1E1106E7, 0x23712F57,
+		0x58F35849, 0x659371F9, 0x22330B29, 0x1F532299,
+		0xAD73FE89, 0x9013D739, 0xD7B3ADE9, 0xEAD38459,
+		0x68831388, 0x55E33A38, 0x124340E8, 0x2F236958,
+		0x9D03B548, 0xA0639CF8, 0xE7C3E628, 0xDAA3CF98,
+		0x3813CFCB, 0x0573E67B, 0x42D39CAB, 0x7FB3B51B,
+		0xCD93690B, 0xF0F340BB, 0xB7533A6B, 0x8A3313DB,
+		0x0863840A, 0x3503ADBA, 0x72A3D76A, 0x4FC3FEDA,
+		0xFDE322CA, 0xC0830B7A, 0x872371AA, 0xBA43581A,
+		0x9932774D, 0xA4525EFD, 0xE3F2242D, 0xDE920D9D,
+		0x6CB2D18D, 0x51D2F83D, 0x167282ED, 0x2B12AB5D,
+		0xA9423C8C, 0x9422153C, 0xD3826FEC, 0xEEE2465C,
+		0x5CC29A4C, 0x61A2B3FC, 0x2602C92C, 0x1B62E09C,
+		0xF9D2E0CF, 0xC4B2C97F, 0x8312B3AF, 0xBE729A1F,
+		0x0C52460F, 0x31326FBF, 0x7692156F, 0x4BF23CDF,
+		0xC9A2AB0E, 0xF4C282BE, 0xB362F86E, 0x8E02D1DE,
+		0x3C220DCE, 0x0142247E, 0x46E25EAE, 0x7B82771E,
+		0xB1E6B092, 0x8C869922, 0xCB26E3F2, 0xF646CA42,
+		0x44661652, 0x79063FE2, 0x3EA64532, 0x03C66C82,
+		0x8196FB53, 0xBCF6D2E3, 0xFB56A833, 0xC6368183,
+		0x74165D93, 0x49767423, 0x0ED60EF3, 0x33B62743,
+		0xD1062710, 0xEC660EA0, 0xABC67470, 0x96A65DC0,
+		0x248681D0, 0x19E6A860, 0x5E46D2B0, 0x6326FB00,
+		0xE1766CD1, 0xDC164561, 0x9BB63FB1, 0xA6D61601,
+		0x14F6CA11, 0x2996E3A1, 0x6E369971, 0x5356B0C1,
+		0x70279F96, 0x4D47B626, 0x0AE7CCF6, 0x3787E546,
+		0x85A73956, 0xB8C710E6, 0xFF676A36, 0xC2074386,
+		0x4057D457, 0x7D37FDE7, 0x3A978737, 0x07F7AE87,
+		0xB5D77297, 0x88B75B27, 0xCF1721F7, 0xF2770847,
+		0x10C70814, 0x2DA721A4, 0x6A075B74, 0x576772C4,
+		0xE547AED4, 0xD8278764, 0x9F87FDB4, 0xA2E7D404,
+		0x20B743D5, 0x1DD76A65, 0x5A7710B5, 0x67173905,
+		0xD537E515, 0xE857CCA5, 0xAFF7B675, 0x92979FC5,
+		0xE915E8DB, 0xD475C16B, 0x93D5BBBB, 0xAEB5920B,
+		0x1C954E1B, 0x21F567AB, 0x66551D7B, 0x5B3534CB,
+		0xD965A31A, 0xE4058AAA, 0xA3A5F07A, 0x9EC5D9CA,
+		0x2CE505DA, 0x11852C6A, 0x562556BA, 0x6B457F0A,
+		0x89F57F59, 0xB49556E9, 0xF3352C39, 0xCE550589,
+		0x7C75D999, 0x4115F029, 0x06B58AF9, 0x3BD5A349,
+		0xB9853498, 0x84E51D28, 0xC34567F8, 0xFE254E48,
+		0x4C059258, 0x7165BBE8, 0x36C5C138, 0x0BA5E888,
+		0x28D4C7DF, 0x15B4EE6F, 0x521494BF, 0x6F74BD0F,
+		0xDD54611F, 0xE03448AF, 0xA794327F, 0x9AF41BCF,
+		0x18A48C1E, 0x25C4A5AE, 0x6264DF7E, 0x5F04F6CE,
+		0xED242ADE, 0xD044036E, 0x97E479BE, 0xAA84500E,
+		0x4834505D, 0x755479ED, 0x32F4033D, 0x0F942A8D,
+		0xBDB4F69D, 0x80D4DF2D, 0xC774A5FD, 0xFA148C4D,
+		0x78441B9C, 0x4524322C, 0x028448FC, 0x3FE4614C,
+		0x8DC4BD5C, 0xB0A494EC, 0xF704EE3C, 0xCA64C78C
+	}, {
+		0x00000000, 0xCB5CD3A5, 0x4DC8A10B, 0x869472AE,
+		0x9B914216, 0x50CD91B3, 0xD659E31D, 0x1D0530B8,
+		0xEC53826D, 0x270F51C8, 0xA19B2366, 0x6AC7F0C3,
+		0x77C2C07B, 0xBC9E13DE, 0x3A0A6170, 0xF156B2D5,
+		0x03D6029B, 0xC88AD13E, 0x4E1EA390, 0x85427035,
+		0x9847408D, 0x531B9328, 0xD58FE186, 0x1ED33223,
+		0xEF8580F6, 0x24D95353, 0xA24D21FD, 0x6911F258,
+		0x7414C2E0, 0xBF481145, 0x39DC63EB, 0xF280B04E,
+		0x07AC0536, 0xCCF0D693, 0x4A64A43D, 0x81387798,
+		0x9C3D4720, 0x57619485, 0xD1F5E62B, 0x1AA9358E,
+		0xEBFF875B, 0x20A354FE, 0xA6372650, 0x6D6BF5F5,
+		0x706EC54D, 0xBB3216E8, 0x3DA66446, 0xF6FAB7E3,
+		0x047A07AD, 0xCF26D408, 0x49B2A6A6, 0x82EE7503,
+		0x9FEB45BB, 0x54B7961E, 0xD223E4B0, 0x197F3715,
+		0xE82985C0, 0x23755665, 0xA5E124CB, 0x6EBDF76E,
+		0x73B8C7D6, 0xB8E41473, 0x3E7066DD, 0xF52CB578,
+		0x0F580A6C, 0xC404D9C9, 0x4290AB67, 0x89CC78C2,
+		0x94C9487A, 0x5F959BDF, 0xD901E971, 0x125D3AD4,
+		0xE30B8801, 0x28575BA4, 0xAEC3290A, 0x659FFAAF,
+		0x789ACA17, 0xB3C619B2, 0x35526B1C, 0xFE0EB8B9,
+		0x0C8E08F7, 0xC7D2DB52, 0x4146A9FC, 0x8A1A7A59,
+		0x971F4AE1, 0x5C439944, 0xDAD7EBEA, 0x118B384F,
+		0xE0DD8A9A, 0x2B81593F, 0xAD152B91, 0x6649F834,
+		0x7B4CC88C, 0xB0101B29, 0x36846987, 0xFDD8BA22,
+		0x08F40F5A, 0xC3A8DCFF, 0x453CAE51, 0x8E607DF4,
+		0x93654D4C, 0x58399EE9, 0xDEADEC47, 0x15F13FE2,
+		0xE4A78D37, 0x2FFB5E92, 0xA96F2C3C, 0x6233FF99,
+		0x7F36CF21, 0xB46A1C84, 0x32FE6E2A, 0xF9A2BD8F,
+		0x0B220DC1, 0xC07EDE64, 0x46EAACCA, 0x8DB67F6F,
+		0x90B34FD7, 0x5BEF9C72, 0xDD7BEEDC, 0x16273D79,
+		0xE7718FAC, 0x2C2D5C09, 0xAAB92EA7, 0x61E5FD02,
+		0x7CE0CDBA, 0xB7BC1E1F, 0x31286CB1, 0xFA74BF14,
+		0x1EB014D8, 0xD5ECC77D, 0x5378B5D3, 0x98246676,
+		0x852156CE, 0x4E7D856B, 0xC8E9F7C5, 0x03B52460,
+		0xF2E396B5, 0x39BF4510, 0xBF2B37BE, 0x7477E41B,
+		0x6972D4A3, 0xA22E0706, 0x24BA75A8, 0xEFE6A60D,
+		0x1D661643, 0xD63AC5E6, 0x50AEB748, 0x9BF264ED,
+		0x86F75455, 0x4DAB87F0, 0xCB3FF55E, 0x006326FB,
+		0xF135942E, 0x3A69478B, 0xBCFD3525, 0x77A1E680,
+		0x6AA4D638, 0xA1F8059D, 0x276C7733, 0xEC30A496,
+		0x191C11EE, 0xD240C24B, 0x54D4B0E5, 0x9F886340,
+		0x828D53F8, 0x49D1805D, 0xCF45F2F3, 0x04192156,
+		0xF54F9383, 0x3E134026, 0xB8873288, 0x73DBE12D,
+		0x6EDED195, 0xA5820230, 0x2316709E, 0xE84AA33B,
+		0x1ACA1375, 0xD196C0D0, 0x5702B27E, 0x9C5E61DB,
+		0x815B5163, 0x4A0782C6, 0xCC93F068, 0x07CF23CD,
+		0xF6999118, 0x3DC542BD, 0xBB513013, 0x700DE3B6,
+		0x6D08D30E, 0xA65400AB, 0x20C07205, 0xEB9CA1A0,
+		0x11E81EB4, 0xDAB4CD11, 0x5C20BFBF, 0x977C6C1A,
+		0x8A795CA2, 0x41258F07, 0xC7B1FDA9, 0x0CED2E0C,
+		0xFDBB9CD9, 0x36E74F7C, 0xB0733DD2, 0x7B2FEE77,
+		0x662ADECF, 0xAD760D6A, 0x2BE27FC4, 0xE0BEAC61,
+		0x123E1C2F, 0xD962CF8A, 0x5FF6BD24, 0x94AA6E81,
+		0x89AF5E39, 0x42F38D9C, 0xC467FF32, 0x0F3B2C97,
+		0xFE6D9E42, 0x35314DE7, 0xB3A53F49, 0x78F9ECEC,
+		0x65FCDC54, 0xAEA00FF1, 0x28347D5F, 0xE368AEFA,
+		0x16441B82, 0xDD18C827, 0x5B8CBA89, 0x90D0692C,
+		0x8DD55994, 0x46898A31, 0xC01DF89F, 0x0B412B3A,
+		0xFA1799EF, 0x314B4A4A, 0xB7DF38E4, 0x7C83EB41,
+		0x6186DBF9, 0xAADA085C, 0x2C4E7AF2, 0xE712A957,
+		0x15921919, 0xDECECABC, 0x585AB812, 0x93066BB7,
+		0x8E035B0F, 0x455F88AA, 0xC3CBFA04, 0x089729A1,
+		0xF9C19B74, 0x329D48D1, 0xB4093A7F, 0x7F55E9DA,
+		0x6250D962, 0xA90C0AC7, 0x2F987869, 0xE4C4ABCC
+	}, {
+		0x00000000, 0xA6770BB4, 0x979F1129, 0x31E81A9D,
+		0xF44F2413, 0x52382FA7, 0x63D0353A, 0xC5A73E8E,
+		0x33EF4E67, 0x959845D3, 0xA4705F4E, 0x020754FA,
+		0xC7A06A74, 0x61D761C0, 0x503F7B5D, 0xF64870E9,
+		0x67DE9CCE, 0xC1A9977A, 0xF0418DE7, 0x56368653,
+		0x9391B8DD, 0x35E6B369, 0x040EA9F4, 0xA279A240,
+		0x5431D2A9, 0xF246D91D, 0xC3AEC380, 0x65D9C834,
+		0xA07EF6BA, 0x0609FD0E, 0x37E1E793, 0x9196EC27,
+		0xCFBD399C, 0x69CA3228, 0x582228B5, 0xFE552301,
+		0x3BF21D8F, 0x9D85163B, 0xAC6D0CA6, 0x0A1A0712,
+		0xFC5277FB, 0x5A257C4F, 0x6BCD66D2, 0xCDBA6D66,
+		0x081D53E8, 0xAE6A585C, 0x9F8242C1, 0x39F54975,
+		0xA863A552, 0x0E14AEE6, 0x3FFCB47B, 0x998BBFCF,
+		0x5C2C8141, 0xFA5B8AF5, 0xCBB39068, 0x6DC49BDC,
+		0x9B8CEB35, 0x3DFBE081, 0x0C13FA1C, 0xAA64F1A8,
+		0x6FC3CF26, 0xC9B4C492, 0xF85CDE0F, 0x5E2BD5BB,
+		0x440B7579, 0xE27C7ECD, 0xD3946450, 0x75E36FE4,
+		0xB044516A, 0x16335ADE, 0x27DB4043, 0x81AC4BF7,
+		0x77E43B1E, 0xD19330AA, 0xE07B2A37, 0x460C2183,
+		0x83AB1F0D, 0x25DC14B9, 0x14340E24, 0xB2430590,
+		0x23D5E9B7, 0x85A2E203, 0xB44AF89E, 0x123DF32A,
+		0xD79ACDA4, 0x71EDC610, 0x4005DC8D, 0xE672D739,
+		0x103AA7D0, 0xB64DAC64, 0x87A5B6F9, 0x21D2BD4D,
+		0xE47583C3, 0x42028877, 0x73EA92EA, 0xD59D995E,
+		0x8BB64CE5, 0x2DC14751, 0x1C295DCC, 0xBA5E5678,
+		0x7FF968F6, 0xD98E6342, 0xE86679DF, 0x4E11726B,
+		0xB8590282, 0x1E2E0936, 0x2FC613AB, 0x89B1181F,
+		0x4C162691, 0xEA612D25, 0xDB8937B8, 0x7DFE3C0C,
+		0xEC68D02B, 0x4A1FDB9F, 0x7BF7C102, 0xDD80CAB6,
+		0x1827F438, 0xBE50FF8C, 0x8FB8E511, 0x29CFEEA5,
+		0xDF879E4C, 0x79F095F8, 0x48188F65, 0xEE6F84D1,
+		0x2BC8BA5F, 0x8DBFB1EB, 0xBC57AB76, 0x1A20A0C2,
+		0x8816EAF2, 0x2E61E146, 0x1F89FBDB, 0xB9FEF06F,
+		0x7C59CEE1, 0xDA2EC555, 0xEBC6DFC8, 0x4DB1D47C,
+		0xBBF9A495, 0x1D8EAF21, 0x2C66B5BC, 0x8A11BE08,
+		0x4FB68086, 0xE9C18B32, 0xD82991AF, 0x7E5E9A1B,
+		0xEFC8763C, 0x49BF7D88, 0x78576715, 0xDE206CA1,
+		0x1B87522F, 0xBDF0599B, 0x8C184306, 0x2A6F48B2,
+		0xDC27385B, 0x7A5033EF, 0x4BB82972, 0xEDCF22C6,
+		0x28681C48, 0x8E1F17FC, 0xBFF70D61, 0x198006D5,
+		0x47ABD36E, 0xE1DCD8DA, 0xD034C247, 0x7643C9F3,
+		0xB3E4F77D, 0x1593FCC9, 0x247BE654, 0x820CEDE0,
+		0x74449D09, 0xD23396BD, 0xE3DB8C20, 0x45AC8794,
+		0x800BB91A, 0x267CB2AE, 0x1794A833, 0xB1E3A387,
+		0x20754FA0, 0x86024414, 0xB7EA5E89, 0x119D553D,
+		0xD43A6BB3, 0x724D6007, 0x43A57A9A, 0xE5D2712E,
+		0x139A01C7, 0xB5ED0A73, 0x840510EE, 0x22721B5A,
+		0xE7D525D4, 0x41A22E60, 0x704A34FD, 0xD63D3F49,
+		0xCC1D9F8B, 0x6A6A943F, 0x5B828EA2, 0xFDF58516,
+		0x3852BB98, 0x9E25B02C, 0xAFCDAAB1, 0x09BAA105,
+		0xFFF2D1EC, 0x5985DA58, 0x686DC0C5, 0xCE1ACB71,
+		0x0BBDF5FF, 0xADCAFE4B, 0x9C22E4D6, 0x3A55EF62,
+		0xABC30345, 0x0DB408F1, 0x3C5C126C, 0x9A2B19D8,
+		0x5F8C2756, 0xF9FB2CE2, 0xC813367F, 0x6E643DCB,
+		0x982C4D22, 0x3E5B4696, 0x0FB35C0B, 0xA9C457BF,
+		0x6C636931, 0xCA146285, 0xFBFC7818, 0x5D8B73AC,
+		0x03A0A617, 0xA5D7ADA3, 0x943FB73E, 0x3248BC8A,
+		0xF7EF8204, 0x519889B0, 0x6070932D, 0xC6079899,
+		0x304FE870, 0x9638E3C4, 0xA7D0F959, 0x01A7F2ED,
+		0xC400CC63, 0x6277C7D7, 0x539FDD4A, 0xF5E8D6FE,
+		0x647E3AD9, 0xC209316D, 0xF3E12BF0, 0x55962044,
+		0x90311ECA, 0x3646157E, 0x07AE0FE3, 0xA1D90457,
+		0x579174BE, 0xF1E67F0A, 0xC00E6597, 0x66796E23,
+		0xA3DE50AD, 0x05A95B19, 0x34414184, 0x92364A30
+	}, {
+		0x00000000, 0xCCAA009E, 0x4225077D, 0x8E8F07E3,
+		0x844A0EFA, 0x48E00E64, 0xC66F0987, 0x0AC50919,
+		0xD3E51BB5, 0x1F4F1B2B, 0x91C01CC8, 0x5D6A1C56,
+		0x57AF154F, 0x9B0515D1, 0x158A1232, 0xD92012AC,
+		0x7CBB312B, 0xB01131B5, 0x3E9E3656, 0xF23436C8,
+		0xF8F13FD1, 0x345B3F4F, 0xBAD438AC, 0x767E3832,
+		0xAF5E2A9E, 0x63F42A00, 0xED7B2DE3, 0x21D12D7D,
+		0x2B142464, 0xE7BE24FA, 0x69312319, 0xA59B2387,
+		0xF9766256, 0x35DC62C8, 0xBB53652B, 0x77F965B5,
+		0x7D3C6CAC, 0xB1966C32, 0x3F196BD1, 0xF3B36B4F,
+		0x2A9379E3, 0xE639797D, 0x68B67E9E, 0xA41C7E00,
+		0xAED97719, 0x62737787, 0xECFC7064, 0x205670FA,
+		0x85CD537D, 0x496753E3, 0xC7E85400, 0x0B42549E,
+		0x01875D87, 0xCD2D5D19, 0x43A25AFA, 0x8F085A64,
+		0x562848C8, 0x9A824856, 0x140D4FB5, 0xD8A74F2B,
+		0xD2624632, 0x1EC846AC, 0x9047414F, 0x5CED41D1,
+		0x299DC2ED, 0xE537C273, 0x6BB8C590, 0xA712C50E,
+		0xADD7CC17, 0x617DCC89, 0xEFF2CB6A, 0x2358CBF4,
+		0xFA78D958, 0x36D2D9C6, 0xB85DDE25, 0x74F7DEBB,
+		0x7E32D7A2, 0xB298D73C, 0x3C17D0DF, 0xF0BDD041,
+		0x5526F3C6, 0x998CF358, 0x1703F4BB, 0xDBA9F425,
+		0xD16CFD3C, 0x1DC6FDA2, 0x9349FA41, 0x5FE3FADF,
+		0x86C3E873, 0x4A69E8ED, 0xC4E6EF0E, 0x084CEF90,
+		0x0289E689, 0xCE23E617, 0x40ACE1F4, 0x8C06E16A,
+		0xD0EBA0BB, 0x1C41A025, 0x92CEA7C6, 0x5E64A758,
+		0x54A1AE41, 0x980BAEDF, 0x1684A93C, 0xDA2EA9A2,
+		0x030EBB0E, 0xCFA4BB90, 0x412BBC73, 0x8D81BCED,
+		0x8744B5F4, 0x4BEEB56A, 0xC561B289, 0x09CBB217,
+		0xAC509190, 0x60FA910E, 0xEE7596ED, 0x22DF9673,
+		0x281A9F6A, 0xE4B09FF4, 0x6A3F9817, 0xA6959889,
+		0x7FB58A25, 0xB31F8ABB, 0x3D908D58, 0xF13A8DC6,
+		0xFBFF84DF, 0x37558441, 0xB9DA83A2, 0x7570833C,
+		0x533B85DA, 0x9F918544, 0x111E82A7, 0xDDB48239,
+		0xD7718B20, 0x1BDB8BBE, 0x95548C5D, 0x59FE8CC3,
+		0x80DE9E6F, 0x4C749EF1, 0xC2FB9912, 0x0E51998C,
+		0x04949095, 0xC83E900B, 0x46B197E8, 0x8A1B9776,
+		0x2F80B4F1, 0xE32AB46F, 0x6DA5B38C, 0xA10FB312,
+		0xABCABA0B, 0x6760BA95, 0xE9EFBD76, 0x2545BDE8,
+		0xFC65AF44, 0x30CFAFDA, 0xBE40A839, 0x72EAA8A7,
+		0x782FA1BE, 0xB485A120, 0x3A0AA6C3, 0xF6A0A65D,
+		0xAA4DE78C, 0x66E7E712, 0xE868E0F1, 0x24C2E06F,
+		0x2E07E976, 0xE2ADE9E8, 0x6C22EE0B, 0xA088EE95,
+		0x79A8FC39, 0xB502FCA7, 0x3B8DFB44, 0xF727FBDA,
+		0xFDE2F2C3, 0x3148F25D, 0xBFC7F5BE, 0x736DF520,
+		0xD6F6D6A7, 0x1A5CD639, 0x94D3D1DA, 0x5879D144,
+		0x52BCD85D, 0x9E16D8C3, 0x1099DF20, 0xDC33DFBE,
+		0x0513CD12, 0xC9B9CD8C, 0x4736CA6F, 0x8B9CCAF1,
+		0x8159C3E8, 0x4DF3C376, 0xC37CC495, 0x0FD6C40B,
+		0x7AA64737, 0xB60C47A9, 0x3883404A, 0xF42940D4,
+		0xFEEC49CD, 0x32464953, 0xBCC94EB0, 0x70634E2E,
+		0xA9435C82, 0x65E95C1C, 0xEB665BFF, 0x27CC5B61,
+		0x2D095278, 0xE1A352E6, 0x6F2C5505, 0xA386559B,
+		0x061D761C, 0xCAB77682, 0x44387161, 0x889271FF,
+		0x825778E6, 0x4EFD7878, 0xC0727F9B, 0x0CD87F05,
+		0xD5F86DA9, 0x19526D37, 0x97DD6AD4, 0x5B776A4A,
+		0x51B26353, 0x9D1863CD, 0x1397642E, 0xDF3D64B0,
+		0x83D02561, 0x4F7A25FF, 0xC1F5221C, 0x0D5F2282,
+		0x079A2B9B, 0xCB302B05, 0x45BF2CE6, 0x89152C78,
+		0x50353ED4, 0x9C9F3E4A, 0x121039A9, 0xDEBA3937,
+		0xD47F302E, 0x18D530B0, 0x965A3753, 0x5AF037CD,
+		0xFF6B144A, 0x33C114D4, 0xBD4E1337, 0x71E413A9,
+		0x7B211AB0, 0xB78B1A2E, 0x39041DCD, 0xF5AE1D53,
+		0x2C8E0FFF, 0xE0240F61, 0x6EAB0882, 0xA201081C,
+		0xA8C40105, 0x646E019B, 0xEAE10678, 0x264B06E6
+	}
+};
diff --git a/Utilities/cmliblzma/liblzma/check/crc32_tablegen.c b/Utilities/cmliblzma/liblzma/check/crc32_tablegen.c
new file mode 100644
index 0000000..31a4d27
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/check/crc32_tablegen.c
@@ -0,0 +1,117 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       crc32_tablegen.c
+/// \brief      Generate crc32_table_le.h and crc32_table_be.h
+///
+/// Compiling: gcc -std=c99 -o crc32_tablegen crc32_tablegen.c
+/// Add -DWORDS_BIGENDIAN to generate big endian table.
+/// Add -DLZ_HASH_TABLE to generate lz_encoder_hash_table.h (little endian).
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include <stdio.h>
+#include "../../common/tuklib_integer.h"
+
+
+static uint32_t crc32_table[8][256];
+
+
+static void
+init_crc32_table(void)
+{
+	static const uint32_t poly32 = UINT32_C(0xEDB88320);
+
+	for (size_t s = 0; s < 8; ++s) {
+		for (size_t b = 0; b < 256; ++b) {
+			uint32_t r = s == 0 ? b : crc32_table[s - 1][b];
+
+			for (size_t i = 0; i < 8; ++i) {
+				if (r & 1)
+					r = (r >> 1) ^ poly32;
+				else
+					r >>= 1;
+			}
+
+			crc32_table[s][b] = r;
+		}
+	}
+
+#ifdef WORDS_BIGENDIAN
+	for (size_t s = 0; s < 8; ++s)
+		for (size_t b = 0; b < 256; ++b)
+			crc32_table[s][b] = bswap32(crc32_table[s][b]);
+#endif
+
+	return;
+}
+
+
+static void
+print_crc32_table(void)
+{
+	printf("/* This file has been automatically generated by "
+			"crc32_tablegen.c. */\n\n"
+			"const uint32_t lzma_crc32_table[8][256] = {\n\t{");
+
+	for (size_t s = 0; s < 8; ++s) {
+		for (size_t b = 0; b < 256; ++b) {
+			if ((b % 4) == 0)
+				printf("\n\t\t");
+
+			printf("0x%08" PRIX32, crc32_table[s][b]);
+
+			if (b != 255)
+				printf(",%s", (b+1) % 4 == 0 ? "" : " ");
+		}
+
+		if (s == 7)
+			printf("\n\t}\n};\n");
+		else
+			printf("\n\t}, {");
+	}
+
+	return;
+}
+
+
+static void
+print_lz_table(void)
+{
+	printf("/* This file has been automatically generated by "
+			"crc32_tablegen.c. */\n\n"
+			"const uint32_t lzma_lz_hash_table[256] = {");
+
+	for (size_t b = 0; b < 256; ++b) {
+		if ((b % 4) == 0)
+			printf("\n\t");
+
+		printf("0x%08" PRIX32, crc32_table[0][b]);
+
+		if (b != 255)
+			printf(",%s", (b+1) % 4 == 0 ? "" : " ");
+	}
+
+	printf("\n};\n");
+
+	return;
+}
+
+
+int
+main(void)
+{
+	init_crc32_table();
+
+#ifdef LZ_HASH_TABLE
+	print_lz_table();
+#else
+	print_crc32_table();
+#endif
+
+	return 0;
+}
diff --git a/Utilities/cmliblzma/liblzma/check/crc32_x86.S b/Utilities/cmliblzma/liblzma/check/crc32_x86.S
new file mode 100644
index 0000000..67f68a4
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/check/crc32_x86.S
@@ -0,0 +1,304 @@
+/*
+ * Speed-optimized CRC32 using slicing-by-eight algorithm
+ *
+ * This uses only i386 instructions, but it is optimized for i686 and later
+ * (including e.g. Pentium II/III/IV, Athlon XP, and Core 2). For i586
+ * (e.g. Pentium), slicing-by-four would be better, and even the C version
+ * of slicing-by-eight built with gcc -march=i586 tends to be a little bit
+ * better than this. Very few probably run this code on i586 or older x86
+ * so this shouldn't be a problem in practice.
+ *
+ * Authors: Igor Pavlov (original version)
+ *          Lasse Collin (AT&T syntax, PIC support, better portability)
+ *
+ * This file has been put into the public domain.
+ * You can do whatever you want with this file.
+ *
+ * This code needs lzma_crc32_table, which can be created using the
+ * following C code:
+
+uint32_t lzma_crc32_table[8][256];
+
+void
+init_table(void)
+{
+	// IEEE-802.3
+	static const uint32_t poly32 = UINT32_C(0xEDB88320);
+
+	// Castagnoli
+	// static const uint32_t poly32 = UINT32_C(0x82F63B78);
+
+	// Koopman
+	// static const uint32_t poly32 = UINT32_C(0xEB31D82E);
+
+	for (size_t s = 0; s < 8; ++s) {
+		for (size_t b = 0; b < 256; ++b) {
+			uint32_t r = s == 0 ? b : lzma_crc32_table[s - 1][b];
+
+			for (size_t i = 0; i < 8; ++i) {
+				if (r & 1)
+					r = (r >> 1) ^ poly32;
+				else
+					r >>= 1;
+			}
+
+			lzma_crc32_table[s][b] = r;
+		}
+	}
+}
+
+ * The prototype of the CRC32 function:
+ * extern uint32_t lzma_crc32(const uint8_t *buf, size_t size, uint32_t crc);
+ */
+
+/*
+ * On some systems, the functions need to be prefixed. The prefix is
+ * usually an underscore.
+ */
+#ifndef __USER_LABEL_PREFIX__
+#	define __USER_LABEL_PREFIX__
+#endif
+#define MAKE_SYM_CAT(prefix, sym) prefix ## sym
+#define MAKE_SYM(prefix, sym) MAKE_SYM_CAT(prefix, sym)
+#define LZMA_CRC32 MAKE_SYM(__USER_LABEL_PREFIX__, lzma_crc32)
+#define LZMA_CRC32_TABLE MAKE_SYM(__USER_LABEL_PREFIX__, lzma_crc32_table)
+
+/*
+ * Solaris assembler doesn't have .p2align, and Darwin uses .align
+ * differently than GNU/Linux and Solaris.
+ */
+#if defined(__APPLE__) || defined(__MSDOS__)
+#	define ALIGN(pow2, abs) .align pow2
+#else
+#	define ALIGN(pow2, abs) .align abs
+#endif
+
+	.text
+	.globl	LZMA_CRC32
+
+#if !defined(__APPLE__) && !defined(_WIN32) && !defined(__CYGWIN__) \
+		&& !defined(__MSDOS__)
+	.type	LZMA_CRC32, @function
+#endif
+
+	ALIGN(4, 16)
+LZMA_CRC32:
+	/*
+	 * Register usage:
+	 * %eax crc
+	 * %esi buf
+	 * %edi size or buf + size
+	 * %ebx lzma_crc32_table
+	 * %ebp Table index
+	 * %ecx Temporary
+	 * %edx Temporary
+	 */
+	pushl	%ebx
+	pushl	%esi
+	pushl	%edi
+	pushl	%ebp
+	movl	0x14(%esp), %esi /* buf */
+	movl	0x18(%esp), %edi /* size */
+	movl	0x1C(%esp), %eax /* crc */
+
+	/*
+	 * Store the address of lzma_crc32_table to %ebx. This is needed to
+	 * get position-independent code (PIC).
+	 *
+	 * The PIC macro is defined by libtool, while __PIC__ is defined
+	 * by GCC but only on some systems. Testing for both makes it simpler
+	 * to test this code without libtool, and keeps the code working also
+	 * when built with libtool but using something else than GCC.
+	 *
+	 * I understood that libtool may define PIC on Windows even though
+	 * the code in Windows DLLs is not PIC in sense that it is in ELF
+	 * binaries, so we need a separate check to always use the non-PIC
+	 * code on Windows.
+	 */
+#if (!defined(PIC) && !defined(__PIC__)) \
+		|| (defined(_WIN32) || defined(__CYGWIN__))
+	/* Not PIC */
+	movl	$ LZMA_CRC32_TABLE, %ebx
+#elif defined(__APPLE__)
+	/* Mach-O */
+	call	.L_get_pc
+.L_pic:
+	leal	.L_lzma_crc32_table$non_lazy_ptr-.L_pic(%ebx), %ebx
+	movl	(%ebx), %ebx
+#else
+	/* ELF */
+	call	.L_get_pc
+	addl	$_GLOBAL_OFFSET_TABLE_, %ebx
+	movl	LZMA_CRC32_TABLE@GOT(%ebx), %ebx
+#endif
+
+	/* Complement the initial value. */
+	notl	%eax
+
+	ALIGN(4, 16)
+.L_align:
+	/*
+	 * Check if there is enough input to use slicing-by-eight.
+	 * We need 16 bytes, because the loop pre-reads eight bytes.
+	 */
+	cmpl	$16, %edi
+	jb	.L_rest
+
+	/* Check if we have reached alignment of eight bytes. */
+	testl	$7, %esi
+	jz	.L_slice
+
+	/* Calculate CRC of the next input byte. */
+	movzbl	(%esi), %ebp
+	incl	%esi
+	movzbl	%al, %ecx
+	xorl	%ecx, %ebp
+	shrl	$8, %eax
+	xorl	(%ebx, %ebp, 4), %eax
+	decl	%edi
+	jmp	.L_align
+
+	ALIGN(2, 4)
+.L_slice:
+	/*
+	 * If we get here, there's at least 16 bytes of aligned input
+	 * available. Make %edi multiple of eight bytes. Store the possible
+	 * remainder over the "size" variable in the argument stack.
+	 */
+	movl	%edi, 0x18(%esp)
+	andl	$-8, %edi
+	subl	%edi, 0x18(%esp)
+
+	/*
+	 * Let %edi be buf + size - 8 while running the main loop. This way
+	 * we can compare for equality to determine when exit the loop.
+	 */
+	addl	%esi, %edi
+	subl	$8, %edi
+
+	/* Read in the first eight aligned bytes. */
+	xorl	(%esi), %eax
+	movl	4(%esi), %ecx
+	movzbl	%cl, %ebp
+
+.L_loop:
+	movl	0x0C00(%ebx, %ebp, 4), %edx
+	movzbl	%ch, %ebp
+	xorl	0x0800(%ebx, %ebp, 4), %edx
+	shrl	$16, %ecx
+	xorl	8(%esi), %edx
+	movzbl	%cl, %ebp
+	xorl	0x0400(%ebx, %ebp, 4), %edx
+	movzbl	%ch, %ebp
+	xorl	(%ebx, %ebp, 4), %edx
+	movzbl	%al, %ebp
+
+	/*
+	 * Read the next four bytes, for which the CRC is calculated
+	 * on the next interation of the loop.
+	 */
+	movl	12(%esi), %ecx
+
+	xorl	0x1C00(%ebx, %ebp, 4), %edx
+	movzbl	%ah, %ebp
+	shrl	$16, %eax
+	xorl	0x1800(%ebx, %ebp, 4), %edx
+	movzbl	%ah, %ebp
+	movzbl	%al, %eax
+	movl	0x1400(%ebx, %eax, 4), %eax
+	addl	$8, %esi
+	xorl	%edx, %eax
+	xorl	0x1000(%ebx, %ebp, 4), %eax
+
+	/* Check for end of aligned input. */
+	cmpl	%edi, %esi
+	movzbl	%cl, %ebp
+	jne	.L_loop
+
+	/*
+	 * Process the remaining eight bytes, which we have already
+	 * copied to %ecx and %edx.
+	 */
+	movl	0x0C00(%ebx, %ebp, 4), %edx
+	movzbl	%ch, %ebp
+	xorl	0x0800(%ebx, %ebp, 4), %edx
+	shrl	$16, %ecx
+	movzbl	%cl, %ebp
+	xorl	0x0400(%ebx, %ebp, 4), %edx
+	movzbl	%ch, %ebp
+	xorl	(%ebx, %ebp, 4), %edx
+	movzbl	%al, %ebp
+
+	xorl	0x1C00(%ebx, %ebp, 4), %edx
+	movzbl	%ah, %ebp
+	shrl	$16, %eax
+	xorl	0x1800(%ebx, %ebp, 4), %edx
+	movzbl	%ah, %ebp
+	movzbl	%al, %eax
+	movl	0x1400(%ebx, %eax, 4), %eax
+	addl	$8, %esi
+	xorl	%edx, %eax
+	xorl	0x1000(%ebx, %ebp, 4), %eax
+
+	/* Copy the number of remaining bytes to %edi. */
+	movl	0x18(%esp), %edi
+
+.L_rest:
+	/* Check for end of input. */
+	testl	%edi, %edi
+	jz	.L_return
+
+	/* Calculate CRC of the next input byte. */
+	movzbl	(%esi), %ebp
+	incl	%esi
+	movzbl	%al, %ecx
+	xorl	%ecx, %ebp
+	shrl	$8, %eax
+	xorl	(%ebx, %ebp, 4), %eax
+	decl	%edi
+	jmp	.L_rest
+
+.L_return:
+	/* Complement the final value. */
+	notl	%eax
+
+	popl	%ebp
+	popl	%edi
+	popl	%esi
+	popl	%ebx
+	ret
+
+#if defined(PIC) || defined(__PIC__)
+	ALIGN(4, 16)
+.L_get_pc:
+	movl	(%esp), %ebx
+	ret
+#endif
+
+#if defined(__APPLE__) && (defined(PIC) || defined(__PIC__))
+	/* Mach-O PIC */
+	.section __IMPORT,__pointers,non_lazy_symbol_pointers
+.L_lzma_crc32_table$non_lazy_ptr:
+	.indirect_symbol LZMA_CRC32_TABLE
+	.long 0
+
+#elif defined(_WIN32) || defined(__CYGWIN__)
+#	ifdef DLL_EXPORT
+	/* This is equivalent of __declspec(dllexport). */
+	.section .drectve
+	.ascii " -export:lzma_crc32"
+#	endif
+
+#elif !defined(__MSDOS__)
+	/* ELF */
+	.size	LZMA_CRC32, .-LZMA_CRC32
+#endif
+
+/*
+ * This is needed to support non-executable stack. It's ugly to
+ * use __linux__ here, but I don't know a way to detect when
+ * we are using GNU assembler.
+ */
+#if defined(__ELF__) && defined(__linux__)
+	.section	.note.GNU-stack,"",@progbits
+#endif
diff --git a/Utilities/cmliblzma/liblzma/check/crc64_fast.c b/Utilities/cmliblzma/liblzma/check/crc64_fast.c
new file mode 100644
index 0000000..1436557
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/check/crc64_fast.c
@@ -0,0 +1,74 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       crc64.c
+/// \brief      CRC64 calculation
+///
+/// Calculate the CRC64 using the slice-by-four algorithm. This is the same
+/// idea that is used in crc32_fast.c, but for CRC64 we use only four tables
+/// instead of eight to avoid increasing CPU cache usage.
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "check.h"
+#include "crc_macros.h"
+
+
+#ifdef WORDS_BIGENDIAN
+#	define A1(x) ((x) >> 56)
+#else
+#	define A1 A
+#endif
+
+
+// See the comments in crc32_fast.c. They aren't duplicated here.
+extern LZMA_API(uint64_t)
+lzma_crc64(const uint8_t *buf, size_t size, uint64_t crc)
+{
+	crc = ~crc;
+
+#ifdef WORDS_BIGENDIAN
+	crc = bswap64(crc);
+#endif
+
+	if (size > 4) {
+		const uint8_t *limit;
+
+		while ((uintptr_t)(buf) & 3) {
+			crc = lzma_crc64_table[0][*buf++ ^ A1(crc)] ^ S8(crc);
+			--size;
+		}
+
+		limit = buf + (size & ~(size_t)(3));
+		size &= (size_t)(3);
+
+		while (buf < limit) {
+#ifdef WORDS_BIGENDIAN
+			const uint32_t tmp = (crc >> 32)
+					^ *(const uint32_t *)(buf);
+#else
+			const uint32_t tmp = crc ^ *(const uint32_t *)(buf);
+#endif
+			buf += 4;
+
+			crc = lzma_crc64_table[3][A(tmp)]
+			    ^ lzma_crc64_table[2][B(tmp)]
+			    ^ S32(crc)
+			    ^ lzma_crc64_table[1][C(tmp)]
+			    ^ lzma_crc64_table[0][D(tmp)];
+		}
+	}
+
+	while (size-- != 0)
+		crc = lzma_crc64_table[0][*buf++ ^ A1(crc)] ^ S8(crc);
+
+#ifdef WORDS_BIGENDIAN
+	crc = bswap64(crc);
+#endif
+
+	return ~crc;
+}
diff --git a/Utilities/cmliblzma/liblzma/check/crc64_small.c b/Utilities/cmliblzma/liblzma/check/crc64_small.c
new file mode 100644
index 0000000..55d7231
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/check/crc64_small.c
@@ -0,0 +1,53 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       crc64_small.c
+/// \brief      CRC64 calculation (size-optimized)
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "check.h"
+
+
+static uint64_t crc64_table[256];
+
+
+static void
+crc64_init(void)
+{
+	static const uint64_t poly64 = UINT64_C(0xC96C5795D7870F42);
+
+	for (size_t b = 0; b < 256; ++b) {
+		uint64_t r = b;
+		for (size_t i = 0; i < 8; ++i) {
+			if (r & 1)
+				r = (r >> 1) ^ poly64;
+			else
+				r >>= 1;
+		}
+
+		crc64_table[b] = r;
+	}
+
+	return;
+}
+
+
+extern LZMA_API(uint64_t)
+lzma_crc64(const uint8_t *buf, size_t size, uint64_t crc)
+{
+	mythread_once(crc64_init);
+
+	crc = ~crc;
+
+	while (size != 0) {
+		crc = crc64_table[*buf++ ^ (crc & 0xFF)] ^ (crc >> 8);
+		--size;
+	}
+
+	return ~crc;
+}
diff --git a/Utilities/cmliblzma/liblzma/check/crc64_table.c b/Utilities/cmliblzma/liblzma/check/crc64_table.c
new file mode 100644
index 0000000..1fbcd94
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/check/crc64_table.c
@@ -0,0 +1,19 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       crc64_table.c
+/// \brief      Precalculated CRC64 table with correct endianness
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "common.h"
+
+#ifdef WORDS_BIGENDIAN
+#	include "crc64_table_be.h"
+#else
+#	include "crc64_table_le.h"
+#endif
diff --git a/Utilities/cmliblzma/liblzma/check/crc64_table_be.h b/Utilities/cmliblzma/liblzma/check/crc64_table_be.h
new file mode 100644
index 0000000..ea074f3
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/check/crc64_table_be.h
@@ -0,0 +1,521 @@
+/* This file has been automatically generated by crc64_tablegen.c. */
+
+const uint64_t lzma_crc64_table[4][256] = {
+	{
+		UINT64_C(0x0000000000000000), UINT64_C(0x6F5FA703BE4C2EB3),
+		UINT64_C(0x5BA040A8573684F4), UINT64_C(0x34FFE7ABE97AAA47),
+		UINT64_C(0x335E8FFF84C3D07B), UINT64_C(0x5C0128FC3A8FFEC8),
+		UINT64_C(0x68FECF57D3F5548F), UINT64_C(0x07A168546DB97A3C),
+		UINT64_C(0x66BC1EFF0987A1F7), UINT64_C(0x09E3B9FCB7CB8F44),
+		UINT64_C(0x3D1C5E575EB12503), UINT64_C(0x5243F954E0FD0BB0),
+		UINT64_C(0x55E291008D44718C), UINT64_C(0x3ABD360333085F3F),
+		UINT64_C(0x0E42D1A8DA72F578), UINT64_C(0x611D76AB643EDBCB),
+		UINT64_C(0x4966335138A19B7D), UINT64_C(0x2639945286EDB5CE),
+		UINT64_C(0x12C673F96F971F89), UINT64_C(0x7D99D4FAD1DB313A),
+		UINT64_C(0x7A38BCAEBC624B06), UINT64_C(0x15671BAD022E65B5),
+		UINT64_C(0x2198FC06EB54CFF2), UINT64_C(0x4EC75B055518E141),
+		UINT64_C(0x2FDA2DAE31263A8A), UINT64_C(0x40858AAD8F6A1439),
+		UINT64_C(0x747A6D066610BE7E), UINT64_C(0x1B25CA05D85C90CD),
+		UINT64_C(0x1C84A251B5E5EAF1), UINT64_C(0x73DB05520BA9C442),
+		UINT64_C(0x4724E2F9E2D36E05), UINT64_C(0x287B45FA5C9F40B6),
+		UINT64_C(0x92CC66A2704237FB), UINT64_C(0xFD93C1A1CE0E1948),
+		UINT64_C(0xC96C260A2774B30F), UINT64_C(0xA633810999389DBC),
+		UINT64_C(0xA192E95DF481E780), UINT64_C(0xCECD4E5E4ACDC933),
+		UINT64_C(0xFA32A9F5A3B76374), UINT64_C(0x956D0EF61DFB4DC7),
+		UINT64_C(0xF470785D79C5960C), UINT64_C(0x9B2FDF5EC789B8BF),
+		UINT64_C(0xAFD038F52EF312F8), UINT64_C(0xC08F9FF690BF3C4B),
+		UINT64_C(0xC72EF7A2FD064677), UINT64_C(0xA87150A1434A68C4),
+		UINT64_C(0x9C8EB70AAA30C283), UINT64_C(0xF3D11009147CEC30),
+		UINT64_C(0xDBAA55F348E3AC86), UINT64_C(0xB4F5F2F0F6AF8235),
+		UINT64_C(0x800A155B1FD52872), UINT64_C(0xEF55B258A19906C1),
+		UINT64_C(0xE8F4DA0CCC207CFD), UINT64_C(0x87AB7D0F726C524E),
+		UINT64_C(0xB3549AA49B16F809), UINT64_C(0xDC0B3DA7255AD6BA),
+		UINT64_C(0xBD164B0C41640D71), UINT64_C(0xD249EC0FFF2823C2),
+		UINT64_C(0xE6B60BA416528985), UINT64_C(0x89E9ACA7A81EA736),
+		UINT64_C(0x8E48C4F3C5A7DD0A), UINT64_C(0xE11763F07BEBF3B9),
+		UINT64_C(0xD5E8845B929159FE), UINT64_C(0xBAB723582CDD774D),
+		UINT64_C(0xA187C3EBCA2BB664), UINT64_C(0xCED864E8746798D7),
+		UINT64_C(0xFA2783439D1D3290), UINT64_C(0x9578244023511C23),
+		UINT64_C(0x92D94C144EE8661F), UINT64_C(0xFD86EB17F0A448AC),
+		UINT64_C(0xC9790CBC19DEE2EB), UINT64_C(0xA626ABBFA792CC58),
+		UINT64_C(0xC73BDD14C3AC1793), UINT64_C(0xA8647A177DE03920),
+		UINT64_C(0x9C9B9DBC949A9367), UINT64_C(0xF3C43ABF2AD6BDD4),
+		UINT64_C(0xF46552EB476FC7E8), UINT64_C(0x9B3AF5E8F923E95B),
+		UINT64_C(0xAFC512431059431C), UINT64_C(0xC09AB540AE156DAF),
+		UINT64_C(0xE8E1F0BAF28A2D19), UINT64_C(0x87BE57B94CC603AA),
+		UINT64_C(0xB341B012A5BCA9ED), UINT64_C(0xDC1E17111BF0875E),
+		UINT64_C(0xDBBF7F457649FD62), UINT64_C(0xB4E0D846C805D3D1),
+		UINT64_C(0x801F3FED217F7996), UINT64_C(0xEF4098EE9F335725),
+		UINT64_C(0x8E5DEE45FB0D8CEE), UINT64_C(0xE10249464541A25D),
+		UINT64_C(0xD5FDAEEDAC3B081A), UINT64_C(0xBAA209EE127726A9),
+		UINT64_C(0xBD0361BA7FCE5C95), UINT64_C(0xD25CC6B9C1827226),
+		UINT64_C(0xE6A3211228F8D861), UINT64_C(0x89FC861196B4F6D2),
+		UINT64_C(0x334BA549BA69819F), UINT64_C(0x5C14024A0425AF2C),
+		UINT64_C(0x68EBE5E1ED5F056B), UINT64_C(0x07B442E253132BD8),
+		UINT64_C(0x00152AB63EAA51E4), UINT64_C(0x6F4A8DB580E67F57),
+		UINT64_C(0x5BB56A1E699CD510), UINT64_C(0x34EACD1DD7D0FBA3),
+		UINT64_C(0x55F7BBB6B3EE2068), UINT64_C(0x3AA81CB50DA20EDB),
+		UINT64_C(0x0E57FB1EE4D8A49C), UINT64_C(0x61085C1D5A948A2F),
+		UINT64_C(0x66A93449372DF013), UINT64_C(0x09F6934A8961DEA0),
+		UINT64_C(0x3D0974E1601B74E7), UINT64_C(0x5256D3E2DE575A54),
+		UINT64_C(0x7A2D961882C81AE2), UINT64_C(0x1572311B3C843451),
+		UINT64_C(0x218DD6B0D5FE9E16), UINT64_C(0x4ED271B36BB2B0A5),
+		UINT64_C(0x497319E7060BCA99), UINT64_C(0x262CBEE4B847E42A),
+		UINT64_C(0x12D3594F513D4E6D), UINT64_C(0x7D8CFE4CEF7160DE),
+		UINT64_C(0x1C9188E78B4FBB15), UINT64_C(0x73CE2FE4350395A6),
+		UINT64_C(0x4731C84FDC793FE1), UINT64_C(0x286E6F4C62351152),
+		UINT64_C(0x2FCF07180F8C6B6E), UINT64_C(0x4090A01BB1C045DD),
+		UINT64_C(0x746F47B058BAEF9A), UINT64_C(0x1B30E0B3E6F6C129),
+		UINT64_C(0x420F87D795576CC9), UINT64_C(0x2D5020D42B1B427A),
+		UINT64_C(0x19AFC77FC261E83D), UINT64_C(0x76F0607C7C2DC68E),
+		UINT64_C(0x715108281194BCB2), UINT64_C(0x1E0EAF2BAFD89201),
+		UINT64_C(0x2AF1488046A23846), UINT64_C(0x45AEEF83F8EE16F5),
+		UINT64_C(0x24B399289CD0CD3E), UINT64_C(0x4BEC3E2B229CE38D),
+		UINT64_C(0x7F13D980CBE649CA), UINT64_C(0x104C7E8375AA6779),
+		UINT64_C(0x17ED16D718131D45), UINT64_C(0x78B2B1D4A65F33F6),
+		UINT64_C(0x4C4D567F4F2599B1), UINT64_C(0x2312F17CF169B702),
+		UINT64_C(0x0B69B486ADF6F7B4), UINT64_C(0x6436138513BAD907),
+		UINT64_C(0x50C9F42EFAC07340), UINT64_C(0x3F96532D448C5DF3),
+		UINT64_C(0x38373B79293527CF), UINT64_C(0x57689C7A9779097C),
+		UINT64_C(0x63977BD17E03A33B), UINT64_C(0x0CC8DCD2C04F8D88),
+		UINT64_C(0x6DD5AA79A4715643), UINT64_C(0x028A0D7A1A3D78F0),
+		UINT64_C(0x3675EAD1F347D2B7), UINT64_C(0x592A4DD24D0BFC04),
+		UINT64_C(0x5E8B258620B28638), UINT64_C(0x31D482859EFEA88B),
+		UINT64_C(0x052B652E778402CC), UINT64_C(0x6A74C22DC9C82C7F),
+		UINT64_C(0xD0C3E175E5155B32), UINT64_C(0xBF9C46765B597581),
+		UINT64_C(0x8B63A1DDB223DFC6), UINT64_C(0xE43C06DE0C6FF175),
+		UINT64_C(0xE39D6E8A61D68B49), UINT64_C(0x8CC2C989DF9AA5FA),
+		UINT64_C(0xB83D2E2236E00FBD), UINT64_C(0xD762892188AC210E),
+		UINT64_C(0xB67FFF8AEC92FAC5), UINT64_C(0xD920588952DED476),
+		UINT64_C(0xEDDFBF22BBA47E31), UINT64_C(0x8280182105E85082),
+		UINT64_C(0x8521707568512ABE), UINT64_C(0xEA7ED776D61D040D),
+		UINT64_C(0xDE8130DD3F67AE4A), UINT64_C(0xB1DE97DE812B80F9),
+		UINT64_C(0x99A5D224DDB4C04F), UINT64_C(0xF6FA752763F8EEFC),
+		UINT64_C(0xC205928C8A8244BB), UINT64_C(0xAD5A358F34CE6A08),
+		UINT64_C(0xAAFB5DDB59771034), UINT64_C(0xC5A4FAD8E73B3E87),
+		UINT64_C(0xF15B1D730E4194C0), UINT64_C(0x9E04BA70B00DBA73),
+		UINT64_C(0xFF19CCDBD43361B8), UINT64_C(0x90466BD86A7F4F0B),
+		UINT64_C(0xA4B98C738305E54C), UINT64_C(0xCBE62B703D49CBFF),
+		UINT64_C(0xCC47432450F0B1C3), UINT64_C(0xA318E427EEBC9F70),
+		UINT64_C(0x97E7038C07C63537), UINT64_C(0xF8B8A48FB98A1B84),
+		UINT64_C(0xE388443C5F7CDAAD), UINT64_C(0x8CD7E33FE130F41E),
+		UINT64_C(0xB8280494084A5E59), UINT64_C(0xD777A397B60670EA),
+		UINT64_C(0xD0D6CBC3DBBF0AD6), UINT64_C(0xBF896CC065F32465),
+		UINT64_C(0x8B768B6B8C898E22), UINT64_C(0xE4292C6832C5A091),
+		UINT64_C(0x85345AC356FB7B5A), UINT64_C(0xEA6BFDC0E8B755E9),
+		UINT64_C(0xDE941A6B01CDFFAE), UINT64_C(0xB1CBBD68BF81D11D),
+		UINT64_C(0xB66AD53CD238AB21), UINT64_C(0xD935723F6C748592),
+		UINT64_C(0xEDCA9594850E2FD5), UINT64_C(0x829532973B420166),
+		UINT64_C(0xAAEE776D67DD41D0), UINT64_C(0xC5B1D06ED9916F63),
+		UINT64_C(0xF14E37C530EBC524), UINT64_C(0x9E1190C68EA7EB97),
+		UINT64_C(0x99B0F892E31E91AB), UINT64_C(0xF6EF5F915D52BF18),
+		UINT64_C(0xC210B83AB428155F), UINT64_C(0xAD4F1F390A643BEC),
+		UINT64_C(0xCC5269926E5AE027), UINT64_C(0xA30DCE91D016CE94),
+		UINT64_C(0x97F2293A396C64D3), UINT64_C(0xF8AD8E3987204A60),
+		UINT64_C(0xFF0CE66DEA99305C), UINT64_C(0x9053416E54D51EEF),
+		UINT64_C(0xA4ACA6C5BDAFB4A8), UINT64_C(0xCBF301C603E39A1B),
+		UINT64_C(0x7144229E2F3EED56), UINT64_C(0x1E1B859D9172C3E5),
+		UINT64_C(0x2AE46236780869A2), UINT64_C(0x45BBC535C6444711),
+		UINT64_C(0x421AAD61ABFD3D2D), UINT64_C(0x2D450A6215B1139E),
+		UINT64_C(0x19BAEDC9FCCBB9D9), UINT64_C(0x76E54ACA4287976A),
+		UINT64_C(0x17F83C6126B94CA1), UINT64_C(0x78A79B6298F56212),
+		UINT64_C(0x4C587CC9718FC855), UINT64_C(0x2307DBCACFC3E6E6),
+		UINT64_C(0x24A6B39EA27A9CDA), UINT64_C(0x4BF9149D1C36B269),
+		UINT64_C(0x7F06F336F54C182E), UINT64_C(0x105954354B00369D),
+		UINT64_C(0x382211CF179F762B), UINT64_C(0x577DB6CCA9D35898),
+		UINT64_C(0x6382516740A9F2DF), UINT64_C(0x0CDDF664FEE5DC6C),
+		UINT64_C(0x0B7C9E30935CA650), UINT64_C(0x642339332D1088E3),
+		UINT64_C(0x50DCDE98C46A22A4), UINT64_C(0x3F83799B7A260C17),
+		UINT64_C(0x5E9E0F301E18D7DC), UINT64_C(0x31C1A833A054F96F),
+		UINT64_C(0x053E4F98492E5328), UINT64_C(0x6A61E89BF7627D9B),
+		UINT64_C(0x6DC080CF9ADB07A7), UINT64_C(0x029F27CC24972914),
+		UINT64_C(0x3660C067CDED8353), UINT64_C(0x593F676473A1ADE0)
+	}, {
+		UINT64_C(0x0000000000000000), UINT64_C(0x0DF1D05C9279E954),
+		UINT64_C(0x1AE2A1B924F3D2A9), UINT64_C(0x171371E5B68A3BFD),
+		UINT64_C(0xB1DA4DDC62497DC1), UINT64_C(0xBC2B9D80F0309495),
+		UINT64_C(0xAB38EC6546BAAF68), UINT64_C(0xA6C93C39D4C3463C),
+		UINT64_C(0xE7AB9517EE3D2210), UINT64_C(0xEA5A454B7C44CB44),
+		UINT64_C(0xFD4934AECACEF0B9), UINT64_C(0xF0B8E4F258B719ED),
+		UINT64_C(0x5671D8CB8C745FD1), UINT64_C(0x5B8008971E0DB685),
+		UINT64_C(0x4C937972A8878D78), UINT64_C(0x4162A92E3AFE642C),
+		UINT64_C(0xCE572B2FDC7B4420), UINT64_C(0xC3A6FB734E02AD74),
+		UINT64_C(0xD4B58A96F8889689), UINT64_C(0xD9445ACA6AF17FDD),
+		UINT64_C(0x7F8D66F3BE3239E1), UINT64_C(0x727CB6AF2C4BD0B5),
+		UINT64_C(0x656FC74A9AC1EB48), UINT64_C(0x689E171608B8021C),
+		UINT64_C(0x29FCBE3832466630), UINT64_C(0x240D6E64A03F8F64),
+		UINT64_C(0x331E1F8116B5B499), UINT64_C(0x3EEFCFDD84CC5DCD),
+		UINT64_C(0x9826F3E4500F1BF1), UINT64_C(0x95D723B8C276F2A5),
+		UINT64_C(0x82C4525D74FCC958), UINT64_C(0x8F358201E685200C),
+		UINT64_C(0x9CAF565EB8F78840), UINT64_C(0x915E86022A8E6114),
+		UINT64_C(0x864DF7E79C045AE9), UINT64_C(0x8BBC27BB0E7DB3BD),
+		UINT64_C(0x2D751B82DABEF581), UINT64_C(0x2084CBDE48C71CD5),
+		UINT64_C(0x3797BA3BFE4D2728), UINT64_C(0x3A666A676C34CE7C),
+		UINT64_C(0x7B04C34956CAAA50), UINT64_C(0x76F51315C4B34304),
+		UINT64_C(0x61E662F0723978F9), UINT64_C(0x6C17B2ACE04091AD),
+		UINT64_C(0xCADE8E953483D791), UINT64_C(0xC72F5EC9A6FA3EC5),
+		UINT64_C(0xD03C2F2C10700538), UINT64_C(0xDDCDFF708209EC6C),
+		UINT64_C(0x52F87D71648CCC60), UINT64_C(0x5F09AD2DF6F52534),
+		UINT64_C(0x481ADCC8407F1EC9), UINT64_C(0x45EB0C94D206F79D),
+		UINT64_C(0xE32230AD06C5B1A1), UINT64_C(0xEED3E0F194BC58F5),
+		UINT64_C(0xF9C0911422366308), UINT64_C(0xF4314148B04F8A5C),
+		UINT64_C(0xB553E8668AB1EE70), UINT64_C(0xB8A2383A18C80724),
+		UINT64_C(0xAFB149DFAE423CD9), UINT64_C(0xA24099833C3BD58D),
+		UINT64_C(0x0489A5BAE8F893B1), UINT64_C(0x097875E67A817AE5),
+		UINT64_C(0x1E6B0403CC0B4118), UINT64_C(0x139AD45F5E72A84C),
+		UINT64_C(0x385FADBC70EF1181), UINT64_C(0x35AE7DE0E296F8D5),
+		UINT64_C(0x22BD0C05541CC328), UINT64_C(0x2F4CDC59C6652A7C),
+		UINT64_C(0x8985E06012A66C40), UINT64_C(0x8474303C80DF8514),
+		UINT64_C(0x936741D93655BEE9), UINT64_C(0x9E969185A42C57BD),
+		UINT64_C(0xDFF438AB9ED23391), UINT64_C(0xD205E8F70CABDAC5),
+		UINT64_C(0xC5169912BA21E138), UINT64_C(0xC8E7494E2858086C),
+		UINT64_C(0x6E2E7577FC9B4E50), UINT64_C(0x63DFA52B6EE2A704),
+		UINT64_C(0x74CCD4CED8689CF9), UINT64_C(0x793D04924A1175AD),
+		UINT64_C(0xF6088693AC9455A1), UINT64_C(0xFBF956CF3EEDBCF5),
+		UINT64_C(0xECEA272A88678708), UINT64_C(0xE11BF7761A1E6E5C),
+		UINT64_C(0x47D2CB4FCEDD2860), UINT64_C(0x4A231B135CA4C134),
+		UINT64_C(0x5D306AF6EA2EFAC9), UINT64_C(0x50C1BAAA7857139D),
+		UINT64_C(0x11A3138442A977B1), UINT64_C(0x1C52C3D8D0D09EE5),
+		UINT64_C(0x0B41B23D665AA518), UINT64_C(0x06B06261F4234C4C),
+		UINT64_C(0xA0795E5820E00A70), UINT64_C(0xAD888E04B299E324),
+		UINT64_C(0xBA9BFFE10413D8D9), UINT64_C(0xB76A2FBD966A318D),
+		UINT64_C(0xA4F0FBE2C81899C1), UINT64_C(0xA9012BBE5A617095),
+		UINT64_C(0xBE125A5BECEB4B68), UINT64_C(0xB3E38A077E92A23C),
+		UINT64_C(0x152AB63EAA51E400), UINT64_C(0x18DB666238280D54),
+		UINT64_C(0x0FC817878EA236A9), UINT64_C(0x0239C7DB1CDBDFFD),
+		UINT64_C(0x435B6EF52625BBD1), UINT64_C(0x4EAABEA9B45C5285),
+		UINT64_C(0x59B9CF4C02D66978), UINT64_C(0x54481F1090AF802C),
+		UINT64_C(0xF2812329446CC610), UINT64_C(0xFF70F375D6152F44),
+		UINT64_C(0xE8638290609F14B9), UINT64_C(0xE59252CCF2E6FDED),
+		UINT64_C(0x6AA7D0CD1463DDE1), UINT64_C(0x67560091861A34B5),
+		UINT64_C(0x7045717430900F48), UINT64_C(0x7DB4A128A2E9E61C),
+		UINT64_C(0xDB7D9D11762AA020), UINT64_C(0xD68C4D4DE4534974),
+		UINT64_C(0xC19F3CA852D97289), UINT64_C(0xCC6EECF4C0A09BDD),
+		UINT64_C(0x8D0C45DAFA5EFFF1), UINT64_C(0x80FD9586682716A5),
+		UINT64_C(0x97EEE463DEAD2D58), UINT64_C(0x9A1F343F4CD4C40C),
+		UINT64_C(0x3CD6080698178230), UINT64_C(0x3127D85A0A6E6B64),
+		UINT64_C(0x2634A9BFBCE45099), UINT64_C(0x2BC579E32E9DB9CD),
+		UINT64_C(0xF5A054D6CA71FB90), UINT64_C(0xF851848A580812C4),
+		UINT64_C(0xEF42F56FEE822939), UINT64_C(0xE2B325337CFBC06D),
+		UINT64_C(0x447A190AA8388651), UINT64_C(0x498BC9563A416F05),
+		UINT64_C(0x5E98B8B38CCB54F8), UINT64_C(0x536968EF1EB2BDAC),
+		UINT64_C(0x120BC1C1244CD980), UINT64_C(0x1FFA119DB63530D4),
+		UINT64_C(0x08E9607800BF0B29), UINT64_C(0x0518B02492C6E27D),
+		UINT64_C(0xA3D18C1D4605A441), UINT64_C(0xAE205C41D47C4D15),
+		UINT64_C(0xB9332DA462F676E8), UINT64_C(0xB4C2FDF8F08F9FBC),
+		UINT64_C(0x3BF77FF9160ABFB0), UINT64_C(0x3606AFA5847356E4),
+		UINT64_C(0x2115DE4032F96D19), UINT64_C(0x2CE40E1CA080844D),
+		UINT64_C(0x8A2D32257443C271), UINT64_C(0x87DCE279E63A2B25),
+		UINT64_C(0x90CF939C50B010D8), UINT64_C(0x9D3E43C0C2C9F98C),
+		UINT64_C(0xDC5CEAEEF8379DA0), UINT64_C(0xD1AD3AB26A4E74F4),
+		UINT64_C(0xC6BE4B57DCC44F09), UINT64_C(0xCB4F9B0B4EBDA65D),
+		UINT64_C(0x6D86A7329A7EE061), UINT64_C(0x6077776E08070935),
+		UINT64_C(0x7764068BBE8D32C8), UINT64_C(0x7A95D6D72CF4DB9C),
+		UINT64_C(0x690F0288728673D0), UINT64_C(0x64FED2D4E0FF9A84),
+		UINT64_C(0x73EDA3315675A179), UINT64_C(0x7E1C736DC40C482D),
+		UINT64_C(0xD8D54F5410CF0E11), UINT64_C(0xD5249F0882B6E745),
+		UINT64_C(0xC237EEED343CDCB8), UINT64_C(0xCFC63EB1A64535EC),
+		UINT64_C(0x8EA4979F9CBB51C0), UINT64_C(0x835547C30EC2B894),
+		UINT64_C(0x94463626B8488369), UINT64_C(0x99B7E67A2A316A3D),
+		UINT64_C(0x3F7EDA43FEF22C01), UINT64_C(0x328F0A1F6C8BC555),
+		UINT64_C(0x259C7BFADA01FEA8), UINT64_C(0x286DABA6487817FC),
+		UINT64_C(0xA75829A7AEFD37F0), UINT64_C(0xAAA9F9FB3C84DEA4),
+		UINT64_C(0xBDBA881E8A0EE559), UINT64_C(0xB04B584218770C0D),
+		UINT64_C(0x1682647BCCB44A31), UINT64_C(0x1B73B4275ECDA365),
+		UINT64_C(0x0C60C5C2E8479898), UINT64_C(0x0191159E7A3E71CC),
+		UINT64_C(0x40F3BCB040C015E0), UINT64_C(0x4D026CECD2B9FCB4),
+		UINT64_C(0x5A111D096433C749), UINT64_C(0x57E0CD55F64A2E1D),
+		UINT64_C(0xF129F16C22896821), UINT64_C(0xFCD82130B0F08175),
+		UINT64_C(0xEBCB50D5067ABA88), UINT64_C(0xE63A8089940353DC),
+		UINT64_C(0xCDFFF96ABA9EEA11), UINT64_C(0xC00E293628E70345),
+		UINT64_C(0xD71D58D39E6D38B8), UINT64_C(0xDAEC888F0C14D1EC),
+		UINT64_C(0x7C25B4B6D8D797D0), UINT64_C(0x71D464EA4AAE7E84),
+		UINT64_C(0x66C7150FFC244579), UINT64_C(0x6B36C5536E5DAC2D),
+		UINT64_C(0x2A546C7D54A3C801), UINT64_C(0x27A5BC21C6DA2155),
+		UINT64_C(0x30B6CDC470501AA8), UINT64_C(0x3D471D98E229F3FC),
+		UINT64_C(0x9B8E21A136EAB5C0), UINT64_C(0x967FF1FDA4935C94),
+		UINT64_C(0x816C801812196769), UINT64_C(0x8C9D504480608E3D),
+		UINT64_C(0x03A8D24566E5AE31), UINT64_C(0x0E590219F49C4765),
+		UINT64_C(0x194A73FC42167C98), UINT64_C(0x14BBA3A0D06F95CC),
+		UINT64_C(0xB2729F9904ACD3F0), UINT64_C(0xBF834FC596D53AA4),
+		UINT64_C(0xA8903E20205F0159), UINT64_C(0xA561EE7CB226E80D),
+		UINT64_C(0xE403475288D88C21), UINT64_C(0xE9F2970E1AA16575),
+		UINT64_C(0xFEE1E6EBAC2B5E88), UINT64_C(0xF31036B73E52B7DC),
+		UINT64_C(0x55D90A8EEA91F1E0), UINT64_C(0x5828DAD278E818B4),
+		UINT64_C(0x4F3BAB37CE622349), UINT64_C(0x42CA7B6B5C1BCA1D),
+		UINT64_C(0x5150AF3402696251), UINT64_C(0x5CA17F6890108B05),
+		UINT64_C(0x4BB20E8D269AB0F8), UINT64_C(0x4643DED1B4E359AC),
+		UINT64_C(0xE08AE2E860201F90), UINT64_C(0xED7B32B4F259F6C4),
+		UINT64_C(0xFA68435144D3CD39), UINT64_C(0xF799930DD6AA246D),
+		UINT64_C(0xB6FB3A23EC544041), UINT64_C(0xBB0AEA7F7E2DA915),
+		UINT64_C(0xAC199B9AC8A792E8), UINT64_C(0xA1E84BC65ADE7BBC),
+		UINT64_C(0x072177FF8E1D3D80), UINT64_C(0x0AD0A7A31C64D4D4),
+		UINT64_C(0x1DC3D646AAEEEF29), UINT64_C(0x1032061A3897067D),
+		UINT64_C(0x9F07841BDE122671), UINT64_C(0x92F654474C6BCF25),
+		UINT64_C(0x85E525A2FAE1F4D8), UINT64_C(0x8814F5FE68981D8C),
+		UINT64_C(0x2EDDC9C7BC5B5BB0), UINT64_C(0x232C199B2E22B2E4),
+		UINT64_C(0x343F687E98A88919), UINT64_C(0x39CEB8220AD1604D),
+		UINT64_C(0x78AC110C302F0461), UINT64_C(0x755DC150A256ED35),
+		UINT64_C(0x624EB0B514DCD6C8), UINT64_C(0x6FBF60E986A53F9C),
+		UINT64_C(0xC9765CD0526679A0), UINT64_C(0xC4878C8CC01F90F4),
+		UINT64_C(0xD394FD697695AB09), UINT64_C(0xDE652D35E4EC425D)
+	}, {
+		UINT64_C(0x0000000000000000), UINT64_C(0xCB6D6A914AE10B3F),
+		UINT64_C(0x96DBD42295C2177E), UINT64_C(0x5DB6BEB3DF231C41),
+		UINT64_C(0x2CB7A9452A852FFC), UINT64_C(0xE7DAC3D4606424C3),
+		UINT64_C(0xBA6C7D67BF473882), UINT64_C(0x710117F6F5A633BD),
+		UINT64_C(0xDD705D247FA5876A), UINT64_C(0x161D37B535448C55),
+		UINT64_C(0x4BAB8906EA679014), UINT64_C(0x80C6E397A0869B2B),
+		UINT64_C(0xF1C7F4615520A896), UINT64_C(0x3AAA9EF01FC1A3A9),
+		UINT64_C(0x671C2043C0E2BFE8), UINT64_C(0xAC714AD28A03B4D7),
+		UINT64_C(0xBAE1BA48FE4A0FD5), UINT64_C(0x718CD0D9B4AB04EA),
+		UINT64_C(0x2C3A6E6A6B8818AB), UINT64_C(0xE75704FB21691394),
+		UINT64_C(0x9656130DD4CF2029), UINT64_C(0x5D3B799C9E2E2B16),
+		UINT64_C(0x008DC72F410D3757), UINT64_C(0xCBE0ADBE0BEC3C68),
+		UINT64_C(0x6791E76C81EF88BF), UINT64_C(0xACFC8DFDCB0E8380),
+		UINT64_C(0xF14A334E142D9FC1), UINT64_C(0x3A2759DF5ECC94FE),
+		UINT64_C(0x4B264E29AB6AA743), UINT64_C(0x804B24B8E18BAC7C),
+		UINT64_C(0xDDFD9A0B3EA8B03D), UINT64_C(0x1690F09A7449BB02),
+		UINT64_C(0xF1DD7B3ED73AC638), UINT64_C(0x3AB011AF9DDBCD07),
+		UINT64_C(0x6706AF1C42F8D146), UINT64_C(0xAC6BC58D0819DA79),
+		UINT64_C(0xDD6AD27BFDBFE9C4), UINT64_C(0x1607B8EAB75EE2FB),
+		UINT64_C(0x4BB10659687DFEBA), UINT64_C(0x80DC6CC8229CF585),
+		UINT64_C(0x2CAD261AA89F4152), UINT64_C(0xE7C04C8BE27E4A6D),
+		UINT64_C(0xBA76F2383D5D562C), UINT64_C(0x711B98A977BC5D13),
+		UINT64_C(0x001A8F5F821A6EAE), UINT64_C(0xCB77E5CEC8FB6591),
+		UINT64_C(0x96C15B7D17D879D0), UINT64_C(0x5DAC31EC5D3972EF),
+		UINT64_C(0x4B3CC1762970C9ED), UINT64_C(0x8051ABE76391C2D2),
+		UINT64_C(0xDDE71554BCB2DE93), UINT64_C(0x168A7FC5F653D5AC),
+		UINT64_C(0x678B683303F5E611), UINT64_C(0xACE602A24914ED2E),
+		UINT64_C(0xF150BC119637F16F), UINT64_C(0x3A3DD680DCD6FA50),
+		UINT64_C(0x964C9C5256D54E87), UINT64_C(0x5D21F6C31C3445B8),
+		UINT64_C(0x00974870C31759F9), UINT64_C(0xCBFA22E189F652C6),
+		UINT64_C(0xBAFB35177C50617B), UINT64_C(0x71965F8636B16A44),
+		UINT64_C(0x2C20E135E9927605), UINT64_C(0xE74D8BA4A3737D3A),
+		UINT64_C(0xE2BBF77CAE758C71), UINT64_C(0x29D69DEDE494874E),
+		UINT64_C(0x7460235E3BB79B0F), UINT64_C(0xBF0D49CF71569030),
+		UINT64_C(0xCE0C5E3984F0A38D), UINT64_C(0x056134A8CE11A8B2),
+		UINT64_C(0x58D78A1B1132B4F3), UINT64_C(0x93BAE08A5BD3BFCC),
+		UINT64_C(0x3FCBAA58D1D00B1B), UINT64_C(0xF4A6C0C99B310024),
+		UINT64_C(0xA9107E7A44121C65), UINT64_C(0x627D14EB0EF3175A),
+		UINT64_C(0x137C031DFB5524E7), UINT64_C(0xD811698CB1B42FD8),
+		UINT64_C(0x85A7D73F6E973399), UINT64_C(0x4ECABDAE247638A6),
+		UINT64_C(0x585A4D34503F83A4), UINT64_C(0x933727A51ADE889B),
+		UINT64_C(0xCE819916C5FD94DA), UINT64_C(0x05ECF3878F1C9FE5),
+		UINT64_C(0x74EDE4717ABAAC58), UINT64_C(0xBF808EE0305BA767),
+		UINT64_C(0xE2363053EF78BB26), UINT64_C(0x295B5AC2A599B019),
+		UINT64_C(0x852A10102F9A04CE), UINT64_C(0x4E477A81657B0FF1),
+		UINT64_C(0x13F1C432BA5813B0), UINT64_C(0xD89CAEA3F0B9188F),
+		UINT64_C(0xA99DB955051F2B32), UINT64_C(0x62F0D3C44FFE200D),
+		UINT64_C(0x3F466D7790DD3C4C), UINT64_C(0xF42B07E6DA3C3773),
+		UINT64_C(0x13668C42794F4A49), UINT64_C(0xD80BE6D333AE4176),
+		UINT64_C(0x85BD5860EC8D5D37), UINT64_C(0x4ED032F1A66C5608),
+		UINT64_C(0x3FD1250753CA65B5), UINT64_C(0xF4BC4F96192B6E8A),
+		UINT64_C(0xA90AF125C60872CB), UINT64_C(0x62679BB48CE979F4),
+		UINT64_C(0xCE16D16606EACD23), UINT64_C(0x057BBBF74C0BC61C),
+		UINT64_C(0x58CD05449328DA5D), UINT64_C(0x93A06FD5D9C9D162),
+		UINT64_C(0xE2A178232C6FE2DF), UINT64_C(0x29CC12B2668EE9E0),
+		UINT64_C(0x747AAC01B9ADF5A1), UINT64_C(0xBF17C690F34CFE9E),
+		UINT64_C(0xA987360A8705459C), UINT64_C(0x62EA5C9BCDE44EA3),
+		UINT64_C(0x3F5CE22812C752E2), UINT64_C(0xF43188B9582659DD),
+		UINT64_C(0x85309F4FAD806A60), UINT64_C(0x4E5DF5DEE761615F),
+		UINT64_C(0x13EB4B6D38427D1E), UINT64_C(0xD88621FC72A37621),
+		UINT64_C(0x74F76B2EF8A0C2F6), UINT64_C(0xBF9A01BFB241C9C9),
+		UINT64_C(0xE22CBF0C6D62D588), UINT64_C(0x2941D59D2783DEB7),
+		UINT64_C(0x5840C26BD225ED0A), UINT64_C(0x932DA8FA98C4E635),
+		UINT64_C(0xCE9B164947E7FA74), UINT64_C(0x05F67CD80D06F14B),
+		UINT64_C(0xC477EFF95CEB18E3), UINT64_C(0x0F1A8568160A13DC),
+		UINT64_C(0x52AC3BDBC9290F9D), UINT64_C(0x99C1514A83C804A2),
+		UINT64_C(0xE8C046BC766E371F), UINT64_C(0x23AD2C2D3C8F3C20),
+		UINT64_C(0x7E1B929EE3AC2061), UINT64_C(0xB576F80FA94D2B5E),
+		UINT64_C(0x1907B2DD234E9F89), UINT64_C(0xD26AD84C69AF94B6),
+		UINT64_C(0x8FDC66FFB68C88F7), UINT64_C(0x44B10C6EFC6D83C8),
+		UINT64_C(0x35B01B9809CBB075), UINT64_C(0xFEDD7109432ABB4A),
+		UINT64_C(0xA36BCFBA9C09A70B), UINT64_C(0x6806A52BD6E8AC34),
+		UINT64_C(0x7E9655B1A2A11736), UINT64_C(0xB5FB3F20E8401C09),
+		UINT64_C(0xE84D819337630048), UINT64_C(0x2320EB027D820B77),
+		UINT64_C(0x5221FCF4882438CA), UINT64_C(0x994C9665C2C533F5),
+		UINT64_C(0xC4FA28D61DE62FB4), UINT64_C(0x0F9742475707248B),
+		UINT64_C(0xA3E60895DD04905C), UINT64_C(0x688B620497E59B63),
+		UINT64_C(0x353DDCB748C68722), UINT64_C(0xFE50B62602278C1D),
+		UINT64_C(0x8F51A1D0F781BFA0), UINT64_C(0x443CCB41BD60B49F),
+		UINT64_C(0x198A75F26243A8DE), UINT64_C(0xD2E71F6328A2A3E1),
+		UINT64_C(0x35AA94C78BD1DEDB), UINT64_C(0xFEC7FE56C130D5E4),
+		UINT64_C(0xA37140E51E13C9A5), UINT64_C(0x681C2A7454F2C29A),
+		UINT64_C(0x191D3D82A154F127), UINT64_C(0xD2705713EBB5FA18),
+		UINT64_C(0x8FC6E9A03496E659), UINT64_C(0x44AB83317E77ED66),
+		UINT64_C(0xE8DAC9E3F47459B1), UINT64_C(0x23B7A372BE95528E),
+		UINT64_C(0x7E011DC161B64ECF), UINT64_C(0xB56C77502B5745F0),
+		UINT64_C(0xC46D60A6DEF1764D), UINT64_C(0x0F000A3794107D72),
+		UINT64_C(0x52B6B4844B336133), UINT64_C(0x99DBDE1501D26A0C),
+		UINT64_C(0x8F4B2E8F759BD10E), UINT64_C(0x4426441E3F7ADA31),
+		UINT64_C(0x1990FAADE059C670), UINT64_C(0xD2FD903CAAB8CD4F),
+		UINT64_C(0xA3FC87CA5F1EFEF2), UINT64_C(0x6891ED5B15FFF5CD),
+		UINT64_C(0x352753E8CADCE98C), UINT64_C(0xFE4A3979803DE2B3),
+		UINT64_C(0x523B73AB0A3E5664), UINT64_C(0x9956193A40DF5D5B),
+		UINT64_C(0xC4E0A7899FFC411A), UINT64_C(0x0F8DCD18D51D4A25),
+		UINT64_C(0x7E8CDAEE20BB7998), UINT64_C(0xB5E1B07F6A5A72A7),
+		UINT64_C(0xE8570ECCB5796EE6), UINT64_C(0x233A645DFF9865D9),
+		UINT64_C(0x26CC1885F29E9492), UINT64_C(0xEDA17214B87F9FAD),
+		UINT64_C(0xB017CCA7675C83EC), UINT64_C(0x7B7AA6362DBD88D3),
+		UINT64_C(0x0A7BB1C0D81BBB6E), UINT64_C(0xC116DB5192FAB051),
+		UINT64_C(0x9CA065E24DD9AC10), UINT64_C(0x57CD0F730738A72F),
+		UINT64_C(0xFBBC45A18D3B13F8), UINT64_C(0x30D12F30C7DA18C7),
+		UINT64_C(0x6D67918318F90486), UINT64_C(0xA60AFB1252180FB9),
+		UINT64_C(0xD70BECE4A7BE3C04), UINT64_C(0x1C668675ED5F373B),
+		UINT64_C(0x41D038C6327C2B7A), UINT64_C(0x8ABD5257789D2045),
+		UINT64_C(0x9C2DA2CD0CD49B47), UINT64_C(0x5740C85C46359078),
+		UINT64_C(0x0AF676EF99168C39), UINT64_C(0xC19B1C7ED3F78706),
+		UINT64_C(0xB09A0B882651B4BB), UINT64_C(0x7BF761196CB0BF84),
+		UINT64_C(0x2641DFAAB393A3C5), UINT64_C(0xED2CB53BF972A8FA),
+		UINT64_C(0x415DFFE973711C2D), UINT64_C(0x8A30957839901712),
+		UINT64_C(0xD7862BCBE6B30B53), UINT64_C(0x1CEB415AAC52006C),
+		UINT64_C(0x6DEA56AC59F433D1), UINT64_C(0xA6873C3D131538EE),
+		UINT64_C(0xFB31828ECC3624AF), UINT64_C(0x305CE81F86D72F90),
+		UINT64_C(0xD71163BB25A452AA), UINT64_C(0x1C7C092A6F455995),
+		UINT64_C(0x41CAB799B06645D4), UINT64_C(0x8AA7DD08FA874EEB),
+		UINT64_C(0xFBA6CAFE0F217D56), UINT64_C(0x30CBA06F45C07669),
+		UINT64_C(0x6D7D1EDC9AE36A28), UINT64_C(0xA610744DD0026117),
+		UINT64_C(0x0A613E9F5A01D5C0), UINT64_C(0xC10C540E10E0DEFF),
+		UINT64_C(0x9CBAEABDCFC3C2BE), UINT64_C(0x57D7802C8522C981),
+		UINT64_C(0x26D697DA7084FA3C), UINT64_C(0xEDBBFD4B3A65F103),
+		UINT64_C(0xB00D43F8E546ED42), UINT64_C(0x7B602969AFA7E67D),
+		UINT64_C(0x6DF0D9F3DBEE5D7F), UINT64_C(0xA69DB362910F5640),
+		UINT64_C(0xFB2B0DD14E2C4A01), UINT64_C(0x3046674004CD413E),
+		UINT64_C(0x414770B6F16B7283), UINT64_C(0x8A2A1A27BB8A79BC),
+		UINT64_C(0xD79CA49464A965FD), UINT64_C(0x1CF1CE052E486EC2),
+		UINT64_C(0xB08084D7A44BDA15), UINT64_C(0x7BEDEE46EEAAD12A),
+		UINT64_C(0x265B50F53189CD6B), UINT64_C(0xED363A647B68C654),
+		UINT64_C(0x9C372D928ECEF5E9), UINT64_C(0x575A4703C42FFED6),
+		UINT64_C(0x0AECF9B01B0CE297), UINT64_C(0xC181932151EDE9A8)
+	}, {
+		UINT64_C(0x0000000000000000), UINT64_C(0xDCA12C225E8AEE1D),
+		UINT64_C(0xB8435944BC14DD3B), UINT64_C(0x64E27566E29E3326),
+		UINT64_C(0x7087B2887829BA77), UINT64_C(0xAC269EAA26A3546A),
+		UINT64_C(0xC8C4EBCCC43D674C), UINT64_C(0x1465C7EE9AB78951),
+		UINT64_C(0xE00E6511F15274EF), UINT64_C(0x3CAF4933AFD89AF2),
+		UINT64_C(0x584D3C554D46A9D4), UINT64_C(0x84EC107713CC47C9),
+		UINT64_C(0x9089D799897BCE98), UINT64_C(0x4C28FBBBD7F12085),
+		UINT64_C(0x28CA8EDD356F13A3), UINT64_C(0xF46BA2FF6BE5FDBE),
+		UINT64_C(0x4503C48DC90A304C), UINT64_C(0x99A2E8AF9780DE51),
+		UINT64_C(0xFD409DC9751EED77), UINT64_C(0x21E1B1EB2B94036A),
+		UINT64_C(0x35847605B1238A3B), UINT64_C(0xE9255A27EFA96426),
+		UINT64_C(0x8DC72F410D375700), UINT64_C(0x5166036353BDB91D),
+		UINT64_C(0xA50DA19C385844A3), UINT64_C(0x79AC8DBE66D2AABE),
+		UINT64_C(0x1D4EF8D8844C9998), UINT64_C(0xC1EFD4FADAC67785),
+		UINT64_C(0xD58A13144071FED4), UINT64_C(0x092B3F361EFB10C9),
+		UINT64_C(0x6DC94A50FC6523EF), UINT64_C(0xB1686672A2EFCDF2),
+		UINT64_C(0x8A06881B93156098), UINT64_C(0x56A7A439CD9F8E85),
+		UINT64_C(0x3245D15F2F01BDA3), UINT64_C(0xEEE4FD7D718B53BE),
+		UINT64_C(0xFA813A93EB3CDAEF), UINT64_C(0x262016B1B5B634F2),
+		UINT64_C(0x42C263D7572807D4), UINT64_C(0x9E634FF509A2E9C9),
+		UINT64_C(0x6A08ED0A62471477), UINT64_C(0xB6A9C1283CCDFA6A),
+		UINT64_C(0xD24BB44EDE53C94C), UINT64_C(0x0EEA986C80D92751),
+		UINT64_C(0x1A8F5F821A6EAE00), UINT64_C(0xC62E73A044E4401D),
+		UINT64_C(0xA2CC06C6A67A733B), UINT64_C(0x7E6D2AE4F8F09D26),
+		UINT64_C(0xCF054C965A1F50D4), UINT64_C(0x13A460B40495BEC9),
+		UINT64_C(0x774615D2E60B8DEF), UINT64_C(0xABE739F0B88163F2),
+		UINT64_C(0xBF82FE1E2236EAA3), UINT64_C(0x6323D23C7CBC04BE),
+		UINT64_C(0x07C1A75A9E223798), UINT64_C(0xDB608B78C0A8D985),
+		UINT64_C(0x2F0B2987AB4D243B), UINT64_C(0xF3AA05A5F5C7CA26),
+		UINT64_C(0x974870C31759F900), UINT64_C(0x4BE95CE149D3171D),
+		UINT64_C(0x5F8C9B0FD3649E4C), UINT64_C(0x832DB72D8DEE7051),
+		UINT64_C(0xE7CFC24B6F704377), UINT64_C(0x3B6EEE6931FAAD6A),
+		UINT64_C(0x91131E980D8418A2), UINT64_C(0x4DB232BA530EF6BF),
+		UINT64_C(0x295047DCB190C599), UINT64_C(0xF5F16BFEEF1A2B84),
+		UINT64_C(0xE194AC1075ADA2D5), UINT64_C(0x3D3580322B274CC8),
+		UINT64_C(0x59D7F554C9B97FEE), UINT64_C(0x8576D976973391F3),
+		UINT64_C(0x711D7B89FCD66C4D), UINT64_C(0xADBC57ABA25C8250),
+		UINT64_C(0xC95E22CD40C2B176), UINT64_C(0x15FF0EEF1E485F6B),
+		UINT64_C(0x019AC90184FFD63A), UINT64_C(0xDD3BE523DA753827),
+		UINT64_C(0xB9D9904538EB0B01), UINT64_C(0x6578BC676661E51C),
+		UINT64_C(0xD410DA15C48E28EE), UINT64_C(0x08B1F6379A04C6F3),
+		UINT64_C(0x6C538351789AF5D5), UINT64_C(0xB0F2AF7326101BC8),
+		UINT64_C(0xA497689DBCA79299), UINT64_C(0x783644BFE22D7C84),
+		UINT64_C(0x1CD431D900B34FA2), UINT64_C(0xC0751DFB5E39A1BF),
+		UINT64_C(0x341EBF0435DC5C01), UINT64_C(0xE8BF93266B56B21C),
+		UINT64_C(0x8C5DE64089C8813A), UINT64_C(0x50FCCA62D7426F27),
+		UINT64_C(0x44990D8C4DF5E676), UINT64_C(0x983821AE137F086B),
+		UINT64_C(0xFCDA54C8F1E13B4D), UINT64_C(0x207B78EAAF6BD550),
+		UINT64_C(0x1B1596839E91783A), UINT64_C(0xC7B4BAA1C01B9627),
+		UINT64_C(0xA356CFC72285A501), UINT64_C(0x7FF7E3E57C0F4B1C),
+		UINT64_C(0x6B92240BE6B8C24D), UINT64_C(0xB7330829B8322C50),
+		UINT64_C(0xD3D17D4F5AAC1F76), UINT64_C(0x0F70516D0426F16B),
+		UINT64_C(0xFB1BF3926FC30CD5), UINT64_C(0x27BADFB03149E2C8),
+		UINT64_C(0x4358AAD6D3D7D1EE), UINT64_C(0x9FF986F48D5D3FF3),
+		UINT64_C(0x8B9C411A17EAB6A2), UINT64_C(0x573D6D38496058BF),
+		UINT64_C(0x33DF185EABFE6B99), UINT64_C(0xEF7E347CF5748584),
+		UINT64_C(0x5E16520E579B4876), UINT64_C(0x82B77E2C0911A66B),
+		UINT64_C(0xE6550B4AEB8F954D), UINT64_C(0x3AF42768B5057B50),
+		UINT64_C(0x2E91E0862FB2F201), UINT64_C(0xF230CCA471381C1C),
+		UINT64_C(0x96D2B9C293A62F3A), UINT64_C(0x4A7395E0CD2CC127),
+		UINT64_C(0xBE18371FA6C93C99), UINT64_C(0x62B91B3DF843D284),
+		UINT64_C(0x065B6E5B1ADDE1A2), UINT64_C(0xDAFA427944570FBF),
+		UINT64_C(0xCE9F8597DEE086EE), UINT64_C(0x123EA9B5806A68F3),
+		UINT64_C(0x76DCDCD362F45BD5), UINT64_C(0xAA7DF0F13C7EB5C8),
+		UINT64_C(0xA739329F30A7E9D6), UINT64_C(0x7B981EBD6E2D07CB),
+		UINT64_C(0x1F7A6BDB8CB334ED), UINT64_C(0xC3DB47F9D239DAF0),
+		UINT64_C(0xD7BE8017488E53A1), UINT64_C(0x0B1FAC351604BDBC),
+		UINT64_C(0x6FFDD953F49A8E9A), UINT64_C(0xB35CF571AA106087),
+		UINT64_C(0x4737578EC1F59D39), UINT64_C(0x9B967BAC9F7F7324),
+		UINT64_C(0xFF740ECA7DE14002), UINT64_C(0x23D522E8236BAE1F),
+		UINT64_C(0x37B0E506B9DC274E), UINT64_C(0xEB11C924E756C953),
+		UINT64_C(0x8FF3BC4205C8FA75), UINT64_C(0x535290605B421468),
+		UINT64_C(0xE23AF612F9ADD99A), UINT64_C(0x3E9BDA30A7273787),
+		UINT64_C(0x5A79AF5645B904A1), UINT64_C(0x86D883741B33EABC),
+		UINT64_C(0x92BD449A818463ED), UINT64_C(0x4E1C68B8DF0E8DF0),
+		UINT64_C(0x2AFE1DDE3D90BED6), UINT64_C(0xF65F31FC631A50CB),
+		UINT64_C(0x0234930308FFAD75), UINT64_C(0xDE95BF2156754368),
+		UINT64_C(0xBA77CA47B4EB704E), UINT64_C(0x66D6E665EA619E53),
+		UINT64_C(0x72B3218B70D61702), UINT64_C(0xAE120DA92E5CF91F),
+		UINT64_C(0xCAF078CFCCC2CA39), UINT64_C(0x165154ED92482424),
+		UINT64_C(0x2D3FBA84A3B2894E), UINT64_C(0xF19E96A6FD386753),
+		UINT64_C(0x957CE3C01FA65475), UINT64_C(0x49DDCFE2412CBA68),
+		UINT64_C(0x5DB8080CDB9B3339), UINT64_C(0x8119242E8511DD24),
+		UINT64_C(0xE5FB5148678FEE02), UINT64_C(0x395A7D6A3905001F),
+		UINT64_C(0xCD31DF9552E0FDA1), UINT64_C(0x1190F3B70C6A13BC),
+		UINT64_C(0x757286D1EEF4209A), UINT64_C(0xA9D3AAF3B07ECE87),
+		UINT64_C(0xBDB66D1D2AC947D6), UINT64_C(0x6117413F7443A9CB),
+		UINT64_C(0x05F5345996DD9AED), UINT64_C(0xD954187BC85774F0),
+		UINT64_C(0x683C7E096AB8B902), UINT64_C(0xB49D522B3432571F),
+		UINT64_C(0xD07F274DD6AC6439), UINT64_C(0x0CDE0B6F88268A24),
+		UINT64_C(0x18BBCC8112910375), UINT64_C(0xC41AE0A34C1BED68),
+		UINT64_C(0xA0F895C5AE85DE4E), UINT64_C(0x7C59B9E7F00F3053),
+		UINT64_C(0x88321B189BEACDED), UINT64_C(0x5493373AC56023F0),
+		UINT64_C(0x3071425C27FE10D6), UINT64_C(0xECD06E7E7974FECB),
+		UINT64_C(0xF8B5A990E3C3779A), UINT64_C(0x241485B2BD499987),
+		UINT64_C(0x40F6F0D45FD7AAA1), UINT64_C(0x9C57DCF6015D44BC),
+		UINT64_C(0x362A2C073D23F174), UINT64_C(0xEA8B002563A91F69),
+		UINT64_C(0x8E69754381372C4F), UINT64_C(0x52C85961DFBDC252),
+		UINT64_C(0x46AD9E8F450A4B03), UINT64_C(0x9A0CB2AD1B80A51E),
+		UINT64_C(0xFEEEC7CBF91E9638), UINT64_C(0x224FEBE9A7947825),
+		UINT64_C(0xD6244916CC71859B), UINT64_C(0x0A85653492FB6B86),
+		UINT64_C(0x6E671052706558A0), UINT64_C(0xB2C63C702EEFB6BD),
+		UINT64_C(0xA6A3FB9EB4583FEC), UINT64_C(0x7A02D7BCEAD2D1F1),
+		UINT64_C(0x1EE0A2DA084CE2D7), UINT64_C(0xC2418EF856C60CCA),
+		UINT64_C(0x7329E88AF429C138), UINT64_C(0xAF88C4A8AAA32F25),
+		UINT64_C(0xCB6AB1CE483D1C03), UINT64_C(0x17CB9DEC16B7F21E),
+		UINT64_C(0x03AE5A028C007B4F), UINT64_C(0xDF0F7620D28A9552),
+		UINT64_C(0xBBED03463014A674), UINT64_C(0x674C2F646E9E4869),
+		UINT64_C(0x93278D9B057BB5D7), UINT64_C(0x4F86A1B95BF15BCA),
+		UINT64_C(0x2B64D4DFB96F68EC), UINT64_C(0xF7C5F8FDE7E586F1),
+		UINT64_C(0xE3A03F137D520FA0), UINT64_C(0x3F01133123D8E1BD),
+		UINT64_C(0x5BE36657C146D29B), UINT64_C(0x87424A759FCC3C86),
+		UINT64_C(0xBC2CA41CAE3691EC), UINT64_C(0x608D883EF0BC7FF1),
+		UINT64_C(0x046FFD5812224CD7), UINT64_C(0xD8CED17A4CA8A2CA),
+		UINT64_C(0xCCAB1694D61F2B9B), UINT64_C(0x100A3AB68895C586),
+		UINT64_C(0x74E84FD06A0BF6A0), UINT64_C(0xA84963F2348118BD),
+		UINT64_C(0x5C22C10D5F64E503), UINT64_C(0x8083ED2F01EE0B1E),
+		UINT64_C(0xE4619849E3703838), UINT64_C(0x38C0B46BBDFAD625),
+		UINT64_C(0x2CA57385274D5F74), UINT64_C(0xF0045FA779C7B169),
+		UINT64_C(0x94E62AC19B59824F), UINT64_C(0x484706E3C5D36C52),
+		UINT64_C(0xF92F6091673CA1A0), UINT64_C(0x258E4CB339B64FBD),
+		UINT64_C(0x416C39D5DB287C9B), UINT64_C(0x9DCD15F785A29286),
+		UINT64_C(0x89A8D2191F151BD7), UINT64_C(0x5509FE3B419FF5CA),
+		UINT64_C(0x31EB8B5DA301C6EC), UINT64_C(0xED4AA77FFD8B28F1),
+		UINT64_C(0x19210580966ED54F), UINT64_C(0xC58029A2C8E43B52),
+		UINT64_C(0xA1625CC42A7A0874), UINT64_C(0x7DC370E674F0E669),
+		UINT64_C(0x69A6B708EE476F38), UINT64_C(0xB5079B2AB0CD8125),
+		UINT64_C(0xD1E5EE4C5253B203), UINT64_C(0x0D44C26E0CD95C1E)
+	}
+};
diff --git a/Utilities/cmliblzma/liblzma/check/crc64_table_le.h b/Utilities/cmliblzma/liblzma/check/crc64_table_le.h
new file mode 100644
index 0000000..1196b31
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/check/crc64_table_le.h
@@ -0,0 +1,521 @@
+/* This file has been automatically generated by crc64_tablegen.c. */
+
+const uint64_t lzma_crc64_table[4][256] = {
+	{
+		UINT64_C(0x0000000000000000), UINT64_C(0xB32E4CBE03A75F6F),
+		UINT64_C(0xF4843657A840A05B), UINT64_C(0x47AA7AE9ABE7FF34),
+		UINT64_C(0x7BD0C384FF8F5E33), UINT64_C(0xC8FE8F3AFC28015C),
+		UINT64_C(0x8F54F5D357CFFE68), UINT64_C(0x3C7AB96D5468A107),
+		UINT64_C(0xF7A18709FF1EBC66), UINT64_C(0x448FCBB7FCB9E309),
+		UINT64_C(0x0325B15E575E1C3D), UINT64_C(0xB00BFDE054F94352),
+		UINT64_C(0x8C71448D0091E255), UINT64_C(0x3F5F08330336BD3A),
+		UINT64_C(0x78F572DAA8D1420E), UINT64_C(0xCBDB3E64AB761D61),
+		UINT64_C(0x7D9BA13851336649), UINT64_C(0xCEB5ED8652943926),
+		UINT64_C(0x891F976FF973C612), UINT64_C(0x3A31DBD1FAD4997D),
+		UINT64_C(0x064B62BCAEBC387A), UINT64_C(0xB5652E02AD1B6715),
+		UINT64_C(0xF2CF54EB06FC9821), UINT64_C(0x41E11855055BC74E),
+		UINT64_C(0x8A3A2631AE2DDA2F), UINT64_C(0x39146A8FAD8A8540),
+		UINT64_C(0x7EBE1066066D7A74), UINT64_C(0xCD905CD805CA251B),
+		UINT64_C(0xF1EAE5B551A2841C), UINT64_C(0x42C4A90B5205DB73),
+		UINT64_C(0x056ED3E2F9E22447), UINT64_C(0xB6409F5CFA457B28),
+		UINT64_C(0xFB374270A266CC92), UINT64_C(0x48190ECEA1C193FD),
+		UINT64_C(0x0FB374270A266CC9), UINT64_C(0xBC9D3899098133A6),
+		UINT64_C(0x80E781F45DE992A1), UINT64_C(0x33C9CD4A5E4ECDCE),
+		UINT64_C(0x7463B7A3F5A932FA), UINT64_C(0xC74DFB1DF60E6D95),
+		UINT64_C(0x0C96C5795D7870F4), UINT64_C(0xBFB889C75EDF2F9B),
+		UINT64_C(0xF812F32EF538D0AF), UINT64_C(0x4B3CBF90F69F8FC0),
+		UINT64_C(0x774606FDA2F72EC7), UINT64_C(0xC4684A43A15071A8),
+		UINT64_C(0x83C230AA0AB78E9C), UINT64_C(0x30EC7C140910D1F3),
+		UINT64_C(0x86ACE348F355AADB), UINT64_C(0x3582AFF6F0F2F5B4),
+		UINT64_C(0x7228D51F5B150A80), UINT64_C(0xC10699A158B255EF),
+		UINT64_C(0xFD7C20CC0CDAF4E8), UINT64_C(0x4E526C720F7DAB87),
+		UINT64_C(0x09F8169BA49A54B3), UINT64_C(0xBAD65A25A73D0BDC),
+		UINT64_C(0x710D64410C4B16BD), UINT64_C(0xC22328FF0FEC49D2),
+		UINT64_C(0x85895216A40BB6E6), UINT64_C(0x36A71EA8A7ACE989),
+		UINT64_C(0x0ADDA7C5F3C4488E), UINT64_C(0xB9F3EB7BF06317E1),
+		UINT64_C(0xFE5991925B84E8D5), UINT64_C(0x4D77DD2C5823B7BA),
+		UINT64_C(0x64B62BCAEBC387A1), UINT64_C(0xD7986774E864D8CE),
+		UINT64_C(0x90321D9D438327FA), UINT64_C(0x231C512340247895),
+		UINT64_C(0x1F66E84E144CD992), UINT64_C(0xAC48A4F017EB86FD),
+		UINT64_C(0xEBE2DE19BC0C79C9), UINT64_C(0x58CC92A7BFAB26A6),
+		UINT64_C(0x9317ACC314DD3BC7), UINT64_C(0x2039E07D177A64A8),
+		UINT64_C(0x67939A94BC9D9B9C), UINT64_C(0xD4BDD62ABF3AC4F3),
+		UINT64_C(0xE8C76F47EB5265F4), UINT64_C(0x5BE923F9E8F53A9B),
+		UINT64_C(0x1C4359104312C5AF), UINT64_C(0xAF6D15AE40B59AC0),
+		UINT64_C(0x192D8AF2BAF0E1E8), UINT64_C(0xAA03C64CB957BE87),
+		UINT64_C(0xEDA9BCA512B041B3), UINT64_C(0x5E87F01B11171EDC),
+		UINT64_C(0x62FD4976457FBFDB), UINT64_C(0xD1D305C846D8E0B4),
+		UINT64_C(0x96797F21ED3F1F80), UINT64_C(0x2557339FEE9840EF),
+		UINT64_C(0xEE8C0DFB45EE5D8E), UINT64_C(0x5DA24145464902E1),
+		UINT64_C(0x1A083BACEDAEFDD5), UINT64_C(0xA9267712EE09A2BA),
+		UINT64_C(0x955CCE7FBA6103BD), UINT64_C(0x267282C1B9C65CD2),
+		UINT64_C(0x61D8F8281221A3E6), UINT64_C(0xD2F6B4961186FC89),
+		UINT64_C(0x9F8169BA49A54B33), UINT64_C(0x2CAF25044A02145C),
+		UINT64_C(0x6B055FEDE1E5EB68), UINT64_C(0xD82B1353E242B407),
+		UINT64_C(0xE451AA3EB62A1500), UINT64_C(0x577FE680B58D4A6F),
+		UINT64_C(0x10D59C691E6AB55B), UINT64_C(0xA3FBD0D71DCDEA34),
+		UINT64_C(0x6820EEB3B6BBF755), UINT64_C(0xDB0EA20DB51CA83A),
+		UINT64_C(0x9CA4D8E41EFB570E), UINT64_C(0x2F8A945A1D5C0861),
+		UINT64_C(0x13F02D374934A966), UINT64_C(0xA0DE61894A93F609),
+		UINT64_C(0xE7741B60E174093D), UINT64_C(0x545A57DEE2D35652),
+		UINT64_C(0xE21AC88218962D7A), UINT64_C(0x5134843C1B317215),
+		UINT64_C(0x169EFED5B0D68D21), UINT64_C(0xA5B0B26BB371D24E),
+		UINT64_C(0x99CA0B06E7197349), UINT64_C(0x2AE447B8E4BE2C26),
+		UINT64_C(0x6D4E3D514F59D312), UINT64_C(0xDE6071EF4CFE8C7D),
+		UINT64_C(0x15BB4F8BE788911C), UINT64_C(0xA6950335E42FCE73),
+		UINT64_C(0xE13F79DC4FC83147), UINT64_C(0x521135624C6F6E28),
+		UINT64_C(0x6E6B8C0F1807CF2F), UINT64_C(0xDD45C0B11BA09040),
+		UINT64_C(0x9AEFBA58B0476F74), UINT64_C(0x29C1F6E6B3E0301B),
+		UINT64_C(0xC96C5795D7870F42), UINT64_C(0x7A421B2BD420502D),
+		UINT64_C(0x3DE861C27FC7AF19), UINT64_C(0x8EC62D7C7C60F076),
+		UINT64_C(0xB2BC941128085171), UINT64_C(0x0192D8AF2BAF0E1E),
+		UINT64_C(0x4638A2468048F12A), UINT64_C(0xF516EEF883EFAE45),
+		UINT64_C(0x3ECDD09C2899B324), UINT64_C(0x8DE39C222B3EEC4B),
+		UINT64_C(0xCA49E6CB80D9137F), UINT64_C(0x7967AA75837E4C10),
+		UINT64_C(0x451D1318D716ED17), UINT64_C(0xF6335FA6D4B1B278),
+		UINT64_C(0xB199254F7F564D4C), UINT64_C(0x02B769F17CF11223),
+		UINT64_C(0xB4F7F6AD86B4690B), UINT64_C(0x07D9BA1385133664),
+		UINT64_C(0x4073C0FA2EF4C950), UINT64_C(0xF35D8C442D53963F),
+		UINT64_C(0xCF273529793B3738), UINT64_C(0x7C0979977A9C6857),
+		UINT64_C(0x3BA3037ED17B9763), UINT64_C(0x888D4FC0D2DCC80C),
+		UINT64_C(0x435671A479AAD56D), UINT64_C(0xF0783D1A7A0D8A02),
+		UINT64_C(0xB7D247F3D1EA7536), UINT64_C(0x04FC0B4DD24D2A59),
+		UINT64_C(0x3886B22086258B5E), UINT64_C(0x8BA8FE9E8582D431),
+		UINT64_C(0xCC0284772E652B05), UINT64_C(0x7F2CC8C92DC2746A),
+		UINT64_C(0x325B15E575E1C3D0), UINT64_C(0x8175595B76469CBF),
+		UINT64_C(0xC6DF23B2DDA1638B), UINT64_C(0x75F16F0CDE063CE4),
+		UINT64_C(0x498BD6618A6E9DE3), UINT64_C(0xFAA59ADF89C9C28C),
+		UINT64_C(0xBD0FE036222E3DB8), UINT64_C(0x0E21AC88218962D7),
+		UINT64_C(0xC5FA92EC8AFF7FB6), UINT64_C(0x76D4DE52895820D9),
+		UINT64_C(0x317EA4BB22BFDFED), UINT64_C(0x8250E80521188082),
+		UINT64_C(0xBE2A516875702185), UINT64_C(0x0D041DD676D77EEA),
+		UINT64_C(0x4AAE673FDD3081DE), UINT64_C(0xF9802B81DE97DEB1),
+		UINT64_C(0x4FC0B4DD24D2A599), UINT64_C(0xFCEEF8632775FAF6),
+		UINT64_C(0xBB44828A8C9205C2), UINT64_C(0x086ACE348F355AAD),
+		UINT64_C(0x34107759DB5DFBAA), UINT64_C(0x873E3BE7D8FAA4C5),
+		UINT64_C(0xC094410E731D5BF1), UINT64_C(0x73BA0DB070BA049E),
+		UINT64_C(0xB86133D4DBCC19FF), UINT64_C(0x0B4F7F6AD86B4690),
+		UINT64_C(0x4CE50583738CB9A4), UINT64_C(0xFFCB493D702BE6CB),
+		UINT64_C(0xC3B1F050244347CC), UINT64_C(0x709FBCEE27E418A3),
+		UINT64_C(0x3735C6078C03E797), UINT64_C(0x841B8AB98FA4B8F8),
+		UINT64_C(0xADDA7C5F3C4488E3), UINT64_C(0x1EF430E13FE3D78C),
+		UINT64_C(0x595E4A08940428B8), UINT64_C(0xEA7006B697A377D7),
+		UINT64_C(0xD60ABFDBC3CBD6D0), UINT64_C(0x6524F365C06C89BF),
+		UINT64_C(0x228E898C6B8B768B), UINT64_C(0x91A0C532682C29E4),
+		UINT64_C(0x5A7BFB56C35A3485), UINT64_C(0xE955B7E8C0FD6BEA),
+		UINT64_C(0xAEFFCD016B1A94DE), UINT64_C(0x1DD181BF68BDCBB1),
+		UINT64_C(0x21AB38D23CD56AB6), UINT64_C(0x9285746C3F7235D9),
+		UINT64_C(0xD52F0E859495CAED), UINT64_C(0x6601423B97329582),
+		UINT64_C(0xD041DD676D77EEAA), UINT64_C(0x636F91D96ED0B1C5),
+		UINT64_C(0x24C5EB30C5374EF1), UINT64_C(0x97EBA78EC690119E),
+		UINT64_C(0xAB911EE392F8B099), UINT64_C(0x18BF525D915FEFF6),
+		UINT64_C(0x5F1528B43AB810C2), UINT64_C(0xEC3B640A391F4FAD),
+		UINT64_C(0x27E05A6E926952CC), UINT64_C(0x94CE16D091CE0DA3),
+		UINT64_C(0xD3646C393A29F297), UINT64_C(0x604A2087398EADF8),
+		UINT64_C(0x5C3099EA6DE60CFF), UINT64_C(0xEF1ED5546E415390),
+		UINT64_C(0xA8B4AFBDC5A6ACA4), UINT64_C(0x1B9AE303C601F3CB),
+		UINT64_C(0x56ED3E2F9E224471), UINT64_C(0xE5C372919D851B1E),
+		UINT64_C(0xA26908783662E42A), UINT64_C(0x114744C635C5BB45),
+		UINT64_C(0x2D3DFDAB61AD1A42), UINT64_C(0x9E13B115620A452D),
+		UINT64_C(0xD9B9CBFCC9EDBA19), UINT64_C(0x6A978742CA4AE576),
+		UINT64_C(0xA14CB926613CF817), UINT64_C(0x1262F598629BA778),
+		UINT64_C(0x55C88F71C97C584C), UINT64_C(0xE6E6C3CFCADB0723),
+		UINT64_C(0xDA9C7AA29EB3A624), UINT64_C(0x69B2361C9D14F94B),
+		UINT64_C(0x2E184CF536F3067F), UINT64_C(0x9D36004B35545910),
+		UINT64_C(0x2B769F17CF112238), UINT64_C(0x9858D3A9CCB67D57),
+		UINT64_C(0xDFF2A94067518263), UINT64_C(0x6CDCE5FE64F6DD0C),
+		UINT64_C(0x50A65C93309E7C0B), UINT64_C(0xE388102D33392364),
+		UINT64_C(0xA4226AC498DEDC50), UINT64_C(0x170C267A9B79833F),
+		UINT64_C(0xDCD7181E300F9E5E), UINT64_C(0x6FF954A033A8C131),
+		UINT64_C(0x28532E49984F3E05), UINT64_C(0x9B7D62F79BE8616A),
+		UINT64_C(0xA707DB9ACF80C06D), UINT64_C(0x14299724CC279F02),
+		UINT64_C(0x5383EDCD67C06036), UINT64_C(0xE0ADA17364673F59)
+	}, {
+		UINT64_C(0x0000000000000000), UINT64_C(0x54E979925CD0F10D),
+		UINT64_C(0xA9D2F324B9A1E21A), UINT64_C(0xFD3B8AB6E5711317),
+		UINT64_C(0xC17D4962DC4DDAB1), UINT64_C(0x959430F0809D2BBC),
+		UINT64_C(0x68AFBA4665EC38AB), UINT64_C(0x3C46C3D4393CC9A6),
+		UINT64_C(0x10223DEE1795ABE7), UINT64_C(0x44CB447C4B455AEA),
+		UINT64_C(0xB9F0CECAAE3449FD), UINT64_C(0xED19B758F2E4B8F0),
+		UINT64_C(0xD15F748CCBD87156), UINT64_C(0x85B60D1E9708805B),
+		UINT64_C(0x788D87A87279934C), UINT64_C(0x2C64FE3A2EA96241),
+		UINT64_C(0x20447BDC2F2B57CE), UINT64_C(0x74AD024E73FBA6C3),
+		UINT64_C(0x899688F8968AB5D4), UINT64_C(0xDD7FF16ACA5A44D9),
+		UINT64_C(0xE13932BEF3668D7F), UINT64_C(0xB5D04B2CAFB67C72),
+		UINT64_C(0x48EBC19A4AC76F65), UINT64_C(0x1C02B80816179E68),
+		UINT64_C(0x3066463238BEFC29), UINT64_C(0x648F3FA0646E0D24),
+		UINT64_C(0x99B4B516811F1E33), UINT64_C(0xCD5DCC84DDCFEF3E),
+		UINT64_C(0xF11B0F50E4F32698), UINT64_C(0xA5F276C2B823D795),
+		UINT64_C(0x58C9FC745D52C482), UINT64_C(0x0C2085E60182358F),
+		UINT64_C(0x4088F7B85E56AF9C), UINT64_C(0x14618E2A02865E91),
+		UINT64_C(0xE95A049CE7F74D86), UINT64_C(0xBDB37D0EBB27BC8B),
+		UINT64_C(0x81F5BEDA821B752D), UINT64_C(0xD51CC748DECB8420),
+		UINT64_C(0x28274DFE3BBA9737), UINT64_C(0x7CCE346C676A663A),
+		UINT64_C(0x50AACA5649C3047B), UINT64_C(0x0443B3C41513F576),
+		UINT64_C(0xF9783972F062E661), UINT64_C(0xAD9140E0ACB2176C),
+		UINT64_C(0x91D78334958EDECA), UINT64_C(0xC53EFAA6C95E2FC7),
+		UINT64_C(0x380570102C2F3CD0), UINT64_C(0x6CEC098270FFCDDD),
+		UINT64_C(0x60CC8C64717DF852), UINT64_C(0x3425F5F62DAD095F),
+		UINT64_C(0xC91E7F40C8DC1A48), UINT64_C(0x9DF706D2940CEB45),
+		UINT64_C(0xA1B1C506AD3022E3), UINT64_C(0xF558BC94F1E0D3EE),
+		UINT64_C(0x086336221491C0F9), UINT64_C(0x5C8A4FB0484131F4),
+		UINT64_C(0x70EEB18A66E853B5), UINT64_C(0x2407C8183A38A2B8),
+		UINT64_C(0xD93C42AEDF49B1AF), UINT64_C(0x8DD53B3C839940A2),
+		UINT64_C(0xB193F8E8BAA58904), UINT64_C(0xE57A817AE6757809),
+		UINT64_C(0x18410BCC03046B1E), UINT64_C(0x4CA8725E5FD49A13),
+		UINT64_C(0x8111EF70BCAD5F38), UINT64_C(0xD5F896E2E07DAE35),
+		UINT64_C(0x28C31C54050CBD22), UINT64_C(0x7C2A65C659DC4C2F),
+		UINT64_C(0x406CA61260E08589), UINT64_C(0x1485DF803C307484),
+		UINT64_C(0xE9BE5536D9416793), UINT64_C(0xBD572CA48591969E),
+		UINT64_C(0x9133D29EAB38F4DF), UINT64_C(0xC5DAAB0CF7E805D2),
+		UINT64_C(0x38E121BA129916C5), UINT64_C(0x6C0858284E49E7C8),
+		UINT64_C(0x504E9BFC77752E6E), UINT64_C(0x04A7E26E2BA5DF63),
+		UINT64_C(0xF99C68D8CED4CC74), UINT64_C(0xAD75114A92043D79),
+		UINT64_C(0xA15594AC938608F6), UINT64_C(0xF5BCED3ECF56F9FB),
+		UINT64_C(0x088767882A27EAEC), UINT64_C(0x5C6E1E1A76F71BE1),
+		UINT64_C(0x6028DDCE4FCBD247), UINT64_C(0x34C1A45C131B234A),
+		UINT64_C(0xC9FA2EEAF66A305D), UINT64_C(0x9D135778AABAC150),
+		UINT64_C(0xB177A9428413A311), UINT64_C(0xE59ED0D0D8C3521C),
+		UINT64_C(0x18A55A663DB2410B), UINT64_C(0x4C4C23F46162B006),
+		UINT64_C(0x700AE020585E79A0), UINT64_C(0x24E399B2048E88AD),
+		UINT64_C(0xD9D81304E1FF9BBA), UINT64_C(0x8D316A96BD2F6AB7),
+		UINT64_C(0xC19918C8E2FBF0A4), UINT64_C(0x9570615ABE2B01A9),
+		UINT64_C(0x684BEBEC5B5A12BE), UINT64_C(0x3CA2927E078AE3B3),
+		UINT64_C(0x00E451AA3EB62A15), UINT64_C(0x540D28386266DB18),
+		UINT64_C(0xA936A28E8717C80F), UINT64_C(0xFDDFDB1CDBC73902),
+		UINT64_C(0xD1BB2526F56E5B43), UINT64_C(0x85525CB4A9BEAA4E),
+		UINT64_C(0x7869D6024CCFB959), UINT64_C(0x2C80AF90101F4854),
+		UINT64_C(0x10C66C44292381F2), UINT64_C(0x442F15D675F370FF),
+		UINT64_C(0xB9149F60908263E8), UINT64_C(0xEDFDE6F2CC5292E5),
+		UINT64_C(0xE1DD6314CDD0A76A), UINT64_C(0xB5341A8691005667),
+		UINT64_C(0x480F903074714570), UINT64_C(0x1CE6E9A228A1B47D),
+		UINT64_C(0x20A02A76119D7DDB), UINT64_C(0x744953E44D4D8CD6),
+		UINT64_C(0x8972D952A83C9FC1), UINT64_C(0xDD9BA0C0F4EC6ECC),
+		UINT64_C(0xF1FF5EFADA450C8D), UINT64_C(0xA51627688695FD80),
+		UINT64_C(0x582DADDE63E4EE97), UINT64_C(0x0CC4D44C3F341F9A),
+		UINT64_C(0x308217980608D63C), UINT64_C(0x646B6E0A5AD82731),
+		UINT64_C(0x9950E4BCBFA93426), UINT64_C(0xCDB99D2EE379C52B),
+		UINT64_C(0x90FB71CAD654A0F5), UINT64_C(0xC41208588A8451F8),
+		UINT64_C(0x392982EE6FF542EF), UINT64_C(0x6DC0FB7C3325B3E2),
+		UINT64_C(0x518638A80A197A44), UINT64_C(0x056F413A56C98B49),
+		UINT64_C(0xF854CB8CB3B8985E), UINT64_C(0xACBDB21EEF686953),
+		UINT64_C(0x80D94C24C1C10B12), UINT64_C(0xD43035B69D11FA1F),
+		UINT64_C(0x290BBF007860E908), UINT64_C(0x7DE2C69224B01805),
+		UINT64_C(0x41A405461D8CD1A3), UINT64_C(0x154D7CD4415C20AE),
+		UINT64_C(0xE876F662A42D33B9), UINT64_C(0xBC9F8FF0F8FDC2B4),
+		UINT64_C(0xB0BF0A16F97FF73B), UINT64_C(0xE4567384A5AF0636),
+		UINT64_C(0x196DF93240DE1521), UINT64_C(0x4D8480A01C0EE42C),
+		UINT64_C(0x71C2437425322D8A), UINT64_C(0x252B3AE679E2DC87),
+		UINT64_C(0xD810B0509C93CF90), UINT64_C(0x8CF9C9C2C0433E9D),
+		UINT64_C(0xA09D37F8EEEA5CDC), UINT64_C(0xF4744E6AB23AADD1),
+		UINT64_C(0x094FC4DC574BBEC6), UINT64_C(0x5DA6BD4E0B9B4FCB),
+		UINT64_C(0x61E07E9A32A7866D), UINT64_C(0x350907086E777760),
+		UINT64_C(0xC8328DBE8B066477), UINT64_C(0x9CDBF42CD7D6957A),
+		UINT64_C(0xD073867288020F69), UINT64_C(0x849AFFE0D4D2FE64),
+		UINT64_C(0x79A1755631A3ED73), UINT64_C(0x2D480CC46D731C7E),
+		UINT64_C(0x110ECF10544FD5D8), UINT64_C(0x45E7B682089F24D5),
+		UINT64_C(0xB8DC3C34EDEE37C2), UINT64_C(0xEC3545A6B13EC6CF),
+		UINT64_C(0xC051BB9C9F97A48E), UINT64_C(0x94B8C20EC3475583),
+		UINT64_C(0x698348B826364694), UINT64_C(0x3D6A312A7AE6B799),
+		UINT64_C(0x012CF2FE43DA7E3F), UINT64_C(0x55C58B6C1F0A8F32),
+		UINT64_C(0xA8FE01DAFA7B9C25), UINT64_C(0xFC177848A6AB6D28),
+		UINT64_C(0xF037FDAEA72958A7), UINT64_C(0xA4DE843CFBF9A9AA),
+		UINT64_C(0x59E50E8A1E88BABD), UINT64_C(0x0D0C771842584BB0),
+		UINT64_C(0x314AB4CC7B648216), UINT64_C(0x65A3CD5E27B4731B),
+		UINT64_C(0x989847E8C2C5600C), UINT64_C(0xCC713E7A9E159101),
+		UINT64_C(0xE015C040B0BCF340), UINT64_C(0xB4FCB9D2EC6C024D),
+		UINT64_C(0x49C73364091D115A), UINT64_C(0x1D2E4AF655CDE057),
+		UINT64_C(0x216889226CF129F1), UINT64_C(0x7581F0B03021D8FC),
+		UINT64_C(0x88BA7A06D550CBEB), UINT64_C(0xDC53039489803AE6),
+		UINT64_C(0x11EA9EBA6AF9FFCD), UINT64_C(0x4503E72836290EC0),
+		UINT64_C(0xB8386D9ED3581DD7), UINT64_C(0xECD1140C8F88ECDA),
+		UINT64_C(0xD097D7D8B6B4257C), UINT64_C(0x847EAE4AEA64D471),
+		UINT64_C(0x794524FC0F15C766), UINT64_C(0x2DAC5D6E53C5366B),
+		UINT64_C(0x01C8A3547D6C542A), UINT64_C(0x5521DAC621BCA527),
+		UINT64_C(0xA81A5070C4CDB630), UINT64_C(0xFCF329E2981D473D),
+		UINT64_C(0xC0B5EA36A1218E9B), UINT64_C(0x945C93A4FDF17F96),
+		UINT64_C(0x6967191218806C81), UINT64_C(0x3D8E608044509D8C),
+		UINT64_C(0x31AEE56645D2A803), UINT64_C(0x65479CF41902590E),
+		UINT64_C(0x987C1642FC734A19), UINT64_C(0xCC956FD0A0A3BB14),
+		UINT64_C(0xF0D3AC04999F72B2), UINT64_C(0xA43AD596C54F83BF),
+		UINT64_C(0x59015F20203E90A8), UINT64_C(0x0DE826B27CEE61A5),
+		UINT64_C(0x218CD888524703E4), UINT64_C(0x7565A11A0E97F2E9),
+		UINT64_C(0x885E2BACEBE6E1FE), UINT64_C(0xDCB7523EB73610F3),
+		UINT64_C(0xE0F191EA8E0AD955), UINT64_C(0xB418E878D2DA2858),
+		UINT64_C(0x492362CE37AB3B4F), UINT64_C(0x1DCA1B5C6B7BCA42),
+		UINT64_C(0x5162690234AF5051), UINT64_C(0x058B1090687FA15C),
+		UINT64_C(0xF8B09A268D0EB24B), UINT64_C(0xAC59E3B4D1DE4346),
+		UINT64_C(0x901F2060E8E28AE0), UINT64_C(0xC4F659F2B4327BED),
+		UINT64_C(0x39CDD344514368FA), UINT64_C(0x6D24AAD60D9399F7),
+		UINT64_C(0x414054EC233AFBB6), UINT64_C(0x15A92D7E7FEA0ABB),
+		UINT64_C(0xE892A7C89A9B19AC), UINT64_C(0xBC7BDE5AC64BE8A1),
+		UINT64_C(0x803D1D8EFF772107), UINT64_C(0xD4D4641CA3A7D00A),
+		UINT64_C(0x29EFEEAA46D6C31D), UINT64_C(0x7D0697381A063210),
+		UINT64_C(0x712612DE1B84079F), UINT64_C(0x25CF6B4C4754F692),
+		UINT64_C(0xD8F4E1FAA225E585), UINT64_C(0x8C1D9868FEF51488),
+		UINT64_C(0xB05B5BBCC7C9DD2E), UINT64_C(0xE4B2222E9B192C23),
+		UINT64_C(0x1989A8987E683F34), UINT64_C(0x4D60D10A22B8CE39),
+		UINT64_C(0x61042F300C11AC78), UINT64_C(0x35ED56A250C15D75),
+		UINT64_C(0xC8D6DC14B5B04E62), UINT64_C(0x9C3FA586E960BF6F),
+		UINT64_C(0xA0796652D05C76C9), UINT64_C(0xF4901FC08C8C87C4),
+		UINT64_C(0x09AB957669FD94D3), UINT64_C(0x5D42ECE4352D65DE)
+	}, {
+		UINT64_C(0x0000000000000000), UINT64_C(0x3F0BE14A916A6DCB),
+		UINT64_C(0x7E17C29522D4DB96), UINT64_C(0x411C23DFB3BEB65D),
+		UINT64_C(0xFC2F852A45A9B72C), UINT64_C(0xC3246460D4C3DAE7),
+		UINT64_C(0x823847BF677D6CBA), UINT64_C(0xBD33A6F5F6170171),
+		UINT64_C(0x6A87A57F245D70DD), UINT64_C(0x558C4435B5371D16),
+		UINT64_C(0x149067EA0689AB4B), UINT64_C(0x2B9B86A097E3C680),
+		UINT64_C(0x96A8205561F4C7F1), UINT64_C(0xA9A3C11FF09EAA3A),
+		UINT64_C(0xE8BFE2C043201C67), UINT64_C(0xD7B4038AD24A71AC),
+		UINT64_C(0xD50F4AFE48BAE1BA), UINT64_C(0xEA04ABB4D9D08C71),
+		UINT64_C(0xAB18886B6A6E3A2C), UINT64_C(0x94136921FB0457E7),
+		UINT64_C(0x2920CFD40D135696), UINT64_C(0x162B2E9E9C793B5D),
+		UINT64_C(0x57370D412FC78D00), UINT64_C(0x683CEC0BBEADE0CB),
+		UINT64_C(0xBF88EF816CE79167), UINT64_C(0x80830ECBFD8DFCAC),
+		UINT64_C(0xC19F2D144E334AF1), UINT64_C(0xFE94CC5EDF59273A),
+		UINT64_C(0x43A76AAB294E264B), UINT64_C(0x7CAC8BE1B8244B80),
+		UINT64_C(0x3DB0A83E0B9AFDDD), UINT64_C(0x02BB49749AF09016),
+		UINT64_C(0x38C63AD73E7BDDF1), UINT64_C(0x07CDDB9DAF11B03A),
+		UINT64_C(0x46D1F8421CAF0667), UINT64_C(0x79DA19088DC56BAC),
+		UINT64_C(0xC4E9BFFD7BD26ADD), UINT64_C(0xFBE25EB7EAB80716),
+		UINT64_C(0xBAFE7D685906B14B), UINT64_C(0x85F59C22C86CDC80),
+		UINT64_C(0x52419FA81A26AD2C), UINT64_C(0x6D4A7EE28B4CC0E7),
+		UINT64_C(0x2C565D3D38F276BA), UINT64_C(0x135DBC77A9981B71),
+		UINT64_C(0xAE6E1A825F8F1A00), UINT64_C(0x9165FBC8CEE577CB),
+		UINT64_C(0xD079D8177D5BC196), UINT64_C(0xEF72395DEC31AC5D),
+		UINT64_C(0xEDC9702976C13C4B), UINT64_C(0xD2C29163E7AB5180),
+		UINT64_C(0x93DEB2BC5415E7DD), UINT64_C(0xACD553F6C57F8A16),
+		UINT64_C(0x11E6F50333688B67), UINT64_C(0x2EED1449A202E6AC),
+		UINT64_C(0x6FF1379611BC50F1), UINT64_C(0x50FAD6DC80D63D3A),
+		UINT64_C(0x874ED556529C4C96), UINT64_C(0xB845341CC3F6215D),
+		UINT64_C(0xF95917C370489700), UINT64_C(0xC652F689E122FACB),
+		UINT64_C(0x7B61507C1735FBBA), UINT64_C(0x446AB136865F9671),
+		UINT64_C(0x057692E935E1202C), UINT64_C(0x3A7D73A3A48B4DE7),
+		UINT64_C(0x718C75AE7CF7BBE2), UINT64_C(0x4E8794E4ED9DD629),
+		UINT64_C(0x0F9BB73B5E236074), UINT64_C(0x30905671CF490DBF),
+		UINT64_C(0x8DA3F084395E0CCE), UINT64_C(0xB2A811CEA8346105),
+		UINT64_C(0xF3B432111B8AD758), UINT64_C(0xCCBFD35B8AE0BA93),
+		UINT64_C(0x1B0BD0D158AACB3F), UINT64_C(0x2400319BC9C0A6F4),
+		UINT64_C(0x651C12447A7E10A9), UINT64_C(0x5A17F30EEB147D62),
+		UINT64_C(0xE72455FB1D037C13), UINT64_C(0xD82FB4B18C6911D8),
+		UINT64_C(0x9933976E3FD7A785), UINT64_C(0xA6387624AEBDCA4E),
+		UINT64_C(0xA4833F50344D5A58), UINT64_C(0x9B88DE1AA5273793),
+		UINT64_C(0xDA94FDC5169981CE), UINT64_C(0xE59F1C8F87F3EC05),
+		UINT64_C(0x58ACBA7A71E4ED74), UINT64_C(0x67A75B30E08E80BF),
+		UINT64_C(0x26BB78EF533036E2), UINT64_C(0x19B099A5C25A5B29),
+		UINT64_C(0xCE049A2F10102A85), UINT64_C(0xF10F7B65817A474E),
+		UINT64_C(0xB01358BA32C4F113), UINT64_C(0x8F18B9F0A3AE9CD8),
+		UINT64_C(0x322B1F0555B99DA9), UINT64_C(0x0D20FE4FC4D3F062),
+		UINT64_C(0x4C3CDD90776D463F), UINT64_C(0x73373CDAE6072BF4),
+		UINT64_C(0x494A4F79428C6613), UINT64_C(0x7641AE33D3E60BD8),
+		UINT64_C(0x375D8DEC6058BD85), UINT64_C(0x08566CA6F132D04E),
+		UINT64_C(0xB565CA530725D13F), UINT64_C(0x8A6E2B19964FBCF4),
+		UINT64_C(0xCB7208C625F10AA9), UINT64_C(0xF479E98CB49B6762),
+		UINT64_C(0x23CDEA0666D116CE), UINT64_C(0x1CC60B4CF7BB7B05),
+		UINT64_C(0x5DDA28934405CD58), UINT64_C(0x62D1C9D9D56FA093),
+		UINT64_C(0xDFE26F2C2378A1E2), UINT64_C(0xE0E98E66B212CC29),
+		UINT64_C(0xA1F5ADB901AC7A74), UINT64_C(0x9EFE4CF390C617BF),
+		UINT64_C(0x9C4505870A3687A9), UINT64_C(0xA34EE4CD9B5CEA62),
+		UINT64_C(0xE252C71228E25C3F), UINT64_C(0xDD592658B98831F4),
+		UINT64_C(0x606A80AD4F9F3085), UINT64_C(0x5F6161E7DEF55D4E),
+		UINT64_C(0x1E7D42386D4BEB13), UINT64_C(0x2176A372FC2186D8),
+		UINT64_C(0xF6C2A0F82E6BF774), UINT64_C(0xC9C941B2BF019ABF),
+		UINT64_C(0x88D5626D0CBF2CE2), UINT64_C(0xB7DE83279DD54129),
+		UINT64_C(0x0AED25D26BC24058), UINT64_C(0x35E6C498FAA82D93),
+		UINT64_C(0x74FAE74749169BCE), UINT64_C(0x4BF1060DD87CF605),
+		UINT64_C(0xE318EB5CF9EF77C4), UINT64_C(0xDC130A1668851A0F),
+		UINT64_C(0x9D0F29C9DB3BAC52), UINT64_C(0xA204C8834A51C199),
+		UINT64_C(0x1F376E76BC46C0E8), UINT64_C(0x203C8F3C2D2CAD23),
+		UINT64_C(0x6120ACE39E921B7E), UINT64_C(0x5E2B4DA90FF876B5),
+		UINT64_C(0x899F4E23DDB20719), UINT64_C(0xB694AF694CD86AD2),
+		UINT64_C(0xF7888CB6FF66DC8F), UINT64_C(0xC8836DFC6E0CB144),
+		UINT64_C(0x75B0CB09981BB035), UINT64_C(0x4ABB2A430971DDFE),
+		UINT64_C(0x0BA7099CBACF6BA3), UINT64_C(0x34ACE8D62BA50668),
+		UINT64_C(0x3617A1A2B155967E), UINT64_C(0x091C40E8203FFBB5),
+		UINT64_C(0x4800633793814DE8), UINT64_C(0x770B827D02EB2023),
+		UINT64_C(0xCA382488F4FC2152), UINT64_C(0xF533C5C265964C99),
+		UINT64_C(0xB42FE61DD628FAC4), UINT64_C(0x8B2407574742970F),
+		UINT64_C(0x5C9004DD9508E6A3), UINT64_C(0x639BE59704628B68),
+		UINT64_C(0x2287C648B7DC3D35), UINT64_C(0x1D8C270226B650FE),
+		UINT64_C(0xA0BF81F7D0A1518F), UINT64_C(0x9FB460BD41CB3C44),
+		UINT64_C(0xDEA84362F2758A19), UINT64_C(0xE1A3A228631FE7D2),
+		UINT64_C(0xDBDED18BC794AA35), UINT64_C(0xE4D530C156FEC7FE),
+		UINT64_C(0xA5C9131EE54071A3), UINT64_C(0x9AC2F254742A1C68),
+		UINT64_C(0x27F154A1823D1D19), UINT64_C(0x18FAB5EB135770D2),
+		UINT64_C(0x59E69634A0E9C68F), UINT64_C(0x66ED777E3183AB44),
+		UINT64_C(0xB15974F4E3C9DAE8), UINT64_C(0x8E5295BE72A3B723),
+		UINT64_C(0xCF4EB661C11D017E), UINT64_C(0xF045572B50776CB5),
+		UINT64_C(0x4D76F1DEA6606DC4), UINT64_C(0x727D1094370A000F),
+		UINT64_C(0x3361334B84B4B652), UINT64_C(0x0C6AD20115DEDB99),
+		UINT64_C(0x0ED19B758F2E4B8F), UINT64_C(0x31DA7A3F1E442644),
+		UINT64_C(0x70C659E0ADFA9019), UINT64_C(0x4FCDB8AA3C90FDD2),
+		UINT64_C(0xF2FE1E5FCA87FCA3), UINT64_C(0xCDF5FF155BED9168),
+		UINT64_C(0x8CE9DCCAE8532735), UINT64_C(0xB3E23D8079394AFE),
+		UINT64_C(0x64563E0AAB733B52), UINT64_C(0x5B5DDF403A195699),
+		UINT64_C(0x1A41FC9F89A7E0C4), UINT64_C(0x254A1DD518CD8D0F),
+		UINT64_C(0x9879BB20EEDA8C7E), UINT64_C(0xA7725A6A7FB0E1B5),
+		UINT64_C(0xE66E79B5CC0E57E8), UINT64_C(0xD96598FF5D643A23),
+		UINT64_C(0x92949EF28518CC26), UINT64_C(0xAD9F7FB81472A1ED),
+		UINT64_C(0xEC835C67A7CC17B0), UINT64_C(0xD388BD2D36A67A7B),
+		UINT64_C(0x6EBB1BD8C0B17B0A), UINT64_C(0x51B0FA9251DB16C1),
+		UINT64_C(0x10ACD94DE265A09C), UINT64_C(0x2FA73807730FCD57),
+		UINT64_C(0xF8133B8DA145BCFB), UINT64_C(0xC718DAC7302FD130),
+		UINT64_C(0x8604F9188391676D), UINT64_C(0xB90F185212FB0AA6),
+		UINT64_C(0x043CBEA7E4EC0BD7), UINT64_C(0x3B375FED7586661C),
+		UINT64_C(0x7A2B7C32C638D041), UINT64_C(0x45209D785752BD8A),
+		UINT64_C(0x479BD40CCDA22D9C), UINT64_C(0x789035465CC84057),
+		UINT64_C(0x398C1699EF76F60A), UINT64_C(0x0687F7D37E1C9BC1),
+		UINT64_C(0xBBB45126880B9AB0), UINT64_C(0x84BFB06C1961F77B),
+		UINT64_C(0xC5A393B3AADF4126), UINT64_C(0xFAA872F93BB52CED),
+		UINT64_C(0x2D1C7173E9FF5D41), UINT64_C(0x121790397895308A),
+		UINT64_C(0x530BB3E6CB2B86D7), UINT64_C(0x6C0052AC5A41EB1C),
+		UINT64_C(0xD133F459AC56EA6D), UINT64_C(0xEE3815133D3C87A6),
+		UINT64_C(0xAF2436CC8E8231FB), UINT64_C(0x902FD7861FE85C30),
+		UINT64_C(0xAA52A425BB6311D7), UINT64_C(0x9559456F2A097C1C),
+		UINT64_C(0xD44566B099B7CA41), UINT64_C(0xEB4E87FA08DDA78A),
+		UINT64_C(0x567D210FFECAA6FB), UINT64_C(0x6976C0456FA0CB30),
+		UINT64_C(0x286AE39ADC1E7D6D), UINT64_C(0x176102D04D7410A6),
+		UINT64_C(0xC0D5015A9F3E610A), UINT64_C(0xFFDEE0100E540CC1),
+		UINT64_C(0xBEC2C3CFBDEABA9C), UINT64_C(0x81C922852C80D757),
+		UINT64_C(0x3CFA8470DA97D626), UINT64_C(0x03F1653A4BFDBBED),
+		UINT64_C(0x42ED46E5F8430DB0), UINT64_C(0x7DE6A7AF6929607B),
+		UINT64_C(0x7F5DEEDBF3D9F06D), UINT64_C(0x40560F9162B39DA6),
+		UINT64_C(0x014A2C4ED10D2BFB), UINT64_C(0x3E41CD0440674630),
+		UINT64_C(0x83726BF1B6704741), UINT64_C(0xBC798ABB271A2A8A),
+		UINT64_C(0xFD65A96494A49CD7), UINT64_C(0xC26E482E05CEF11C),
+		UINT64_C(0x15DA4BA4D78480B0), UINT64_C(0x2AD1AAEE46EEED7B),
+		UINT64_C(0x6BCD8931F5505B26), UINT64_C(0x54C6687B643A36ED),
+		UINT64_C(0xE9F5CE8E922D379C), UINT64_C(0xD6FE2FC403475A57),
+		UINT64_C(0x97E20C1BB0F9EC0A), UINT64_C(0xA8E9ED51219381C1)
+	}, {
+		UINT64_C(0x0000000000000000), UINT64_C(0x1DEE8A5E222CA1DC),
+		UINT64_C(0x3BDD14BC445943B8), UINT64_C(0x26339EE26675E264),
+		UINT64_C(0x77BA297888B28770), UINT64_C(0x6A54A326AA9E26AC),
+		UINT64_C(0x4C673DC4CCEBC4C8), UINT64_C(0x5189B79AEEC76514),
+		UINT64_C(0xEF7452F111650EE0), UINT64_C(0xF29AD8AF3349AF3C),
+		UINT64_C(0xD4A9464D553C4D58), UINT64_C(0xC947CC137710EC84),
+		UINT64_C(0x98CE7B8999D78990), UINT64_C(0x8520F1D7BBFB284C),
+		UINT64_C(0xA3136F35DD8ECA28), UINT64_C(0xBEFDE56BFFA26BF4),
+		UINT64_C(0x4C300AC98DC40345), UINT64_C(0x51DE8097AFE8A299),
+		UINT64_C(0x77ED1E75C99D40FD), UINT64_C(0x6A03942BEBB1E121),
+		UINT64_C(0x3B8A23B105768435), UINT64_C(0x2664A9EF275A25E9),
+		UINT64_C(0x0057370D412FC78D), UINT64_C(0x1DB9BD5363036651),
+		UINT64_C(0xA34458389CA10DA5), UINT64_C(0xBEAAD266BE8DAC79),
+		UINT64_C(0x98994C84D8F84E1D), UINT64_C(0x8577C6DAFAD4EFC1),
+		UINT64_C(0xD4FE714014138AD5), UINT64_C(0xC910FB1E363F2B09),
+		UINT64_C(0xEF2365FC504AC96D), UINT64_C(0xF2CDEFA2726668B1),
+		UINT64_C(0x986015931B88068A), UINT64_C(0x858E9FCD39A4A756),
+		UINT64_C(0xA3BD012F5FD14532), UINT64_C(0xBE538B717DFDE4EE),
+		UINT64_C(0xEFDA3CEB933A81FA), UINT64_C(0xF234B6B5B1162026),
+		UINT64_C(0xD4072857D763C242), UINT64_C(0xC9E9A209F54F639E),
+		UINT64_C(0x771447620AED086A), UINT64_C(0x6AFACD3C28C1A9B6),
+		UINT64_C(0x4CC953DE4EB44BD2), UINT64_C(0x5127D9806C98EA0E),
+		UINT64_C(0x00AE6E1A825F8F1A), UINT64_C(0x1D40E444A0732EC6),
+		UINT64_C(0x3B737AA6C606CCA2), UINT64_C(0x269DF0F8E42A6D7E),
+		UINT64_C(0xD4501F5A964C05CF), UINT64_C(0xC9BE9504B460A413),
+		UINT64_C(0xEF8D0BE6D2154677), UINT64_C(0xF26381B8F039E7AB),
+		UINT64_C(0xA3EA36221EFE82BF), UINT64_C(0xBE04BC7C3CD22363),
+		UINT64_C(0x9837229E5AA7C107), UINT64_C(0x85D9A8C0788B60DB),
+		UINT64_C(0x3B244DAB87290B2F), UINT64_C(0x26CAC7F5A505AAF3),
+		UINT64_C(0x00F95917C3704897), UINT64_C(0x1D17D349E15CE94B),
+		UINT64_C(0x4C9E64D30F9B8C5F), UINT64_C(0x5170EE8D2DB72D83),
+		UINT64_C(0x7743706F4BC2CFE7), UINT64_C(0x6AADFA3169EE6E3B),
+		UINT64_C(0xA218840D981E1391), UINT64_C(0xBFF60E53BA32B24D),
+		UINT64_C(0x99C590B1DC475029), UINT64_C(0x842B1AEFFE6BF1F5),
+		UINT64_C(0xD5A2AD7510AC94E1), UINT64_C(0xC84C272B3280353D),
+		UINT64_C(0xEE7FB9C954F5D759), UINT64_C(0xF391339776D97685),
+		UINT64_C(0x4D6CD6FC897B1D71), UINT64_C(0x50825CA2AB57BCAD),
+		UINT64_C(0x76B1C240CD225EC9), UINT64_C(0x6B5F481EEF0EFF15),
+		UINT64_C(0x3AD6FF8401C99A01), UINT64_C(0x273875DA23E53BDD),
+		UINT64_C(0x010BEB384590D9B9), UINT64_C(0x1CE5616667BC7865),
+		UINT64_C(0xEE288EC415DA10D4), UINT64_C(0xF3C6049A37F6B108),
+		UINT64_C(0xD5F59A785183536C), UINT64_C(0xC81B102673AFF2B0),
+		UINT64_C(0x9992A7BC9D6897A4), UINT64_C(0x847C2DE2BF443678),
+		UINT64_C(0xA24FB300D931D41C), UINT64_C(0xBFA1395EFB1D75C0),
+		UINT64_C(0x015CDC3504BF1E34), UINT64_C(0x1CB2566B2693BFE8),
+		UINT64_C(0x3A81C88940E65D8C), UINT64_C(0x276F42D762CAFC50),
+		UINT64_C(0x76E6F54D8C0D9944), UINT64_C(0x6B087F13AE213898),
+		UINT64_C(0x4D3BE1F1C854DAFC), UINT64_C(0x50D56BAFEA787B20),
+		UINT64_C(0x3A78919E8396151B), UINT64_C(0x27961BC0A1BAB4C7),
+		UINT64_C(0x01A58522C7CF56A3), UINT64_C(0x1C4B0F7CE5E3F77F),
+		UINT64_C(0x4DC2B8E60B24926B), UINT64_C(0x502C32B8290833B7),
+		UINT64_C(0x761FAC5A4F7DD1D3), UINT64_C(0x6BF126046D51700F),
+		UINT64_C(0xD50CC36F92F31BFB), UINT64_C(0xC8E24931B0DFBA27),
+		UINT64_C(0xEED1D7D3D6AA5843), UINT64_C(0xF33F5D8DF486F99F),
+		UINT64_C(0xA2B6EA171A419C8B), UINT64_C(0xBF586049386D3D57),
+		UINT64_C(0x996BFEAB5E18DF33), UINT64_C(0x848574F57C347EEF),
+		UINT64_C(0x76489B570E52165E), UINT64_C(0x6BA611092C7EB782),
+		UINT64_C(0x4D958FEB4A0B55E6), UINT64_C(0x507B05B56827F43A),
+		UINT64_C(0x01F2B22F86E0912E), UINT64_C(0x1C1C3871A4CC30F2),
+		UINT64_C(0x3A2FA693C2B9D296), UINT64_C(0x27C12CCDE095734A),
+		UINT64_C(0x993CC9A61F3718BE), UINT64_C(0x84D243F83D1BB962),
+		UINT64_C(0xA2E1DD1A5B6E5B06), UINT64_C(0xBF0F57447942FADA),
+		UINT64_C(0xEE86E0DE97859FCE), UINT64_C(0xF3686A80B5A93E12),
+		UINT64_C(0xD55BF462D3DCDC76), UINT64_C(0xC8B57E3CF1F07DAA),
+		UINT64_C(0xD6E9A7309F3239A7), UINT64_C(0xCB072D6EBD1E987B),
+		UINT64_C(0xED34B38CDB6B7A1F), UINT64_C(0xF0DA39D2F947DBC3),
+		UINT64_C(0xA1538E481780BED7), UINT64_C(0xBCBD041635AC1F0B),
+		UINT64_C(0x9A8E9AF453D9FD6F), UINT64_C(0x876010AA71F55CB3),
+		UINT64_C(0x399DF5C18E573747), UINT64_C(0x24737F9FAC7B969B),
+		UINT64_C(0x0240E17DCA0E74FF), UINT64_C(0x1FAE6B23E822D523),
+		UINT64_C(0x4E27DCB906E5B037), UINT64_C(0x53C956E724C911EB),
+		UINT64_C(0x75FAC80542BCF38F), UINT64_C(0x6814425B60905253),
+		UINT64_C(0x9AD9ADF912F63AE2), UINT64_C(0x873727A730DA9B3E),
+		UINT64_C(0xA104B94556AF795A), UINT64_C(0xBCEA331B7483D886),
+		UINT64_C(0xED6384819A44BD92), UINT64_C(0xF08D0EDFB8681C4E),
+		UINT64_C(0xD6BE903DDE1DFE2A), UINT64_C(0xCB501A63FC315FF6),
+		UINT64_C(0x75ADFF0803933402), UINT64_C(0x6843755621BF95DE),
+		UINT64_C(0x4E70EBB447CA77BA), UINT64_C(0x539E61EA65E6D666),
+		UINT64_C(0x0217D6708B21B372), UINT64_C(0x1FF95C2EA90D12AE),
+		UINT64_C(0x39CAC2CCCF78F0CA), UINT64_C(0x24244892ED545116),
+		UINT64_C(0x4E89B2A384BA3F2D), UINT64_C(0x536738FDA6969EF1),
+		UINT64_C(0x7554A61FC0E37C95), UINT64_C(0x68BA2C41E2CFDD49),
+		UINT64_C(0x39339BDB0C08B85D), UINT64_C(0x24DD11852E241981),
+		UINT64_C(0x02EE8F674851FBE5), UINT64_C(0x1F0005396A7D5A39),
+		UINT64_C(0xA1FDE05295DF31CD), UINT64_C(0xBC136A0CB7F39011),
+		UINT64_C(0x9A20F4EED1867275), UINT64_C(0x87CE7EB0F3AAD3A9),
+		UINT64_C(0xD647C92A1D6DB6BD), UINT64_C(0xCBA943743F411761),
+		UINT64_C(0xED9ADD965934F505), UINT64_C(0xF07457C87B1854D9),
+		UINT64_C(0x02B9B86A097E3C68), UINT64_C(0x1F5732342B529DB4),
+		UINT64_C(0x3964ACD64D277FD0), UINT64_C(0x248A26886F0BDE0C),
+		UINT64_C(0x7503911281CCBB18), UINT64_C(0x68ED1B4CA3E01AC4),
+		UINT64_C(0x4EDE85AEC595F8A0), UINT64_C(0x53300FF0E7B9597C),
+		UINT64_C(0xEDCDEA9B181B3288), UINT64_C(0xF02360C53A379354),
+		UINT64_C(0xD610FE275C427130), UINT64_C(0xCBFE74797E6ED0EC),
+		UINT64_C(0x9A77C3E390A9B5F8), UINT64_C(0x879949BDB2851424),
+		UINT64_C(0xA1AAD75FD4F0F640), UINT64_C(0xBC445D01F6DC579C),
+		UINT64_C(0x74F1233D072C2A36), UINT64_C(0x691FA96325008BEA),
+		UINT64_C(0x4F2C37814375698E), UINT64_C(0x52C2BDDF6159C852),
+		UINT64_C(0x034B0A458F9EAD46), UINT64_C(0x1EA5801BADB20C9A),
+		UINT64_C(0x38961EF9CBC7EEFE), UINT64_C(0x257894A7E9EB4F22),
+		UINT64_C(0x9B8571CC164924D6), UINT64_C(0x866BFB923465850A),
+		UINT64_C(0xA05865705210676E), UINT64_C(0xBDB6EF2E703CC6B2),
+		UINT64_C(0xEC3F58B49EFBA3A6), UINT64_C(0xF1D1D2EABCD7027A),
+		UINT64_C(0xD7E24C08DAA2E01E), UINT64_C(0xCA0CC656F88E41C2),
+		UINT64_C(0x38C129F48AE82973), UINT64_C(0x252FA3AAA8C488AF),
+		UINT64_C(0x031C3D48CEB16ACB), UINT64_C(0x1EF2B716EC9DCB17),
+		UINT64_C(0x4F7B008C025AAE03), UINT64_C(0x52958AD220760FDF),
+		UINT64_C(0x74A614304603EDBB), UINT64_C(0x69489E6E642F4C67),
+		UINT64_C(0xD7B57B059B8D2793), UINT64_C(0xCA5BF15BB9A1864F),
+		UINT64_C(0xEC686FB9DFD4642B), UINT64_C(0xF186E5E7FDF8C5F7),
+		UINT64_C(0xA00F527D133FA0E3), UINT64_C(0xBDE1D8233113013F),
+		UINT64_C(0x9BD246C15766E35B), UINT64_C(0x863CCC9F754A4287),
+		UINT64_C(0xEC9136AE1CA42CBC), UINT64_C(0xF17FBCF03E888D60),
+		UINT64_C(0xD74C221258FD6F04), UINT64_C(0xCAA2A84C7AD1CED8),
+		UINT64_C(0x9B2B1FD69416ABCC), UINT64_C(0x86C59588B63A0A10),
+		UINT64_C(0xA0F60B6AD04FE874), UINT64_C(0xBD188134F26349A8),
+		UINT64_C(0x03E5645F0DC1225C), UINT64_C(0x1E0BEE012FED8380),
+		UINT64_C(0x383870E3499861E4), UINT64_C(0x25D6FABD6BB4C038),
+		UINT64_C(0x745F4D278573A52C), UINT64_C(0x69B1C779A75F04F0),
+		UINT64_C(0x4F82599BC12AE694), UINT64_C(0x526CD3C5E3064748),
+		UINT64_C(0xA0A13C6791602FF9), UINT64_C(0xBD4FB639B34C8E25),
+		UINT64_C(0x9B7C28DBD5396C41), UINT64_C(0x8692A285F715CD9D),
+		UINT64_C(0xD71B151F19D2A889), UINT64_C(0xCAF59F413BFE0955),
+		UINT64_C(0xECC601A35D8BEB31), UINT64_C(0xF1288BFD7FA74AED),
+		UINT64_C(0x4FD56E9680052119), UINT64_C(0x523BE4C8A22980C5),
+		UINT64_C(0x74087A2AC45C62A1), UINT64_C(0x69E6F074E670C37D),
+		UINT64_C(0x386F47EE08B7A669), UINT64_C(0x2581CDB02A9B07B5),
+		UINT64_C(0x03B253524CEEE5D1), UINT64_C(0x1E5CD90C6EC2440D)
+	}
+};
diff --git a/Utilities/cmliblzma/liblzma/check/crc64_tablegen.c b/Utilities/cmliblzma/liblzma/check/crc64_tablegen.c
new file mode 100644
index 0000000..fddaa7e
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/check/crc64_tablegen.c
@@ -0,0 +1,88 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       crc64_tablegen.c
+/// \brief      Generate crc64_table_le.h and crc64_table_be.h
+///
+/// Compiling: gcc -std=c99 -o crc64_tablegen crc64_tablegen.c
+/// Add -DWORDS_BIGENDIAN to generate big endian table.
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include <stdio.h>
+#include "../../common/tuklib_integer.h"
+
+
+static uint64_t crc64_table[4][256];
+
+
+extern void
+init_crc64_table(void)
+{
+	static const uint64_t poly64 = UINT64_C(0xC96C5795D7870F42);
+
+	for (size_t s = 0; s < 4; ++s) {
+		for (size_t b = 0; b < 256; ++b) {
+			uint64_t r = s == 0 ? b : crc64_table[s - 1][b];
+
+			for (size_t i = 0; i < 8; ++i) {
+				if (r & 1)
+					r = (r >> 1) ^ poly64;
+				else
+					r >>= 1;
+			}
+
+			crc64_table[s][b] = r;
+		}
+	}
+
+#ifdef WORDS_BIGENDIAN
+	for (size_t s = 0; s < 4; ++s)
+		for (size_t b = 0; b < 256; ++b)
+			crc64_table[s][b] = bswap64(crc64_table[s][b]);
+#endif
+
+	return;
+}
+
+
+static void
+print_crc64_table(void)
+{
+	printf("/* This file has been automatically generated by "
+			"crc64_tablegen.c. */\n\n"
+			"const uint64_t lzma_crc64_table[4][256] = {\n\t{");
+
+	for (size_t s = 0; s < 4; ++s) {
+		for (size_t b = 0; b < 256; ++b) {
+			if ((b % 2) == 0)
+				printf("\n\t\t");
+
+			printf("UINT64_C(0x%016" PRIX64 ")",
+					crc64_table[s][b]);
+
+			if (b != 255)
+				printf(",%s", (b+1) % 2 == 0 ? "" : " ");
+		}
+
+		if (s == 3)
+			printf("\n\t}\n};\n");
+		else
+			printf("\n\t}, {");
+	}
+
+	return;
+}
+
+
+int
+main(void)
+{
+	init_crc64_table();
+	print_crc64_table();
+	return 0;
+}
diff --git a/Utilities/cmliblzma/liblzma/check/crc64_x86.S b/Utilities/cmliblzma/liblzma/check/crc64_x86.S
new file mode 100644
index 0000000..f5bb84b
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/check/crc64_x86.S
@@ -0,0 +1,287 @@
+/*
+ * Speed-optimized CRC64 using slicing-by-four algorithm
+ *
+ * This uses only i386 instructions, but it is optimized for i686 and later
+ * (including e.g. Pentium II/III/IV, Athlon XP, and Core 2).
+ *
+ * Authors: Igor Pavlov (original CRC32 assembly code)
+ *          Lasse Collin (CRC64 adaptation of the modified CRC32 code)
+ *
+ * This file has been put into the public domain.
+ * You can do whatever you want with this file.
+ *
+ * This code needs lzma_crc64_table, which can be created using the
+ * following C code:
+
+uint64_t lzma_crc64_table[4][256];
+
+void
+init_table(void)
+{
+	// ECMA-182
+	static const uint64_t poly64 = UINT64_C(0xC96C5795D7870F42);
+
+	for (size_t s = 0; s < 4; ++s) {
+		for (size_t b = 0; b < 256; ++b) {
+			uint64_t r = s == 0 ? b : lzma_crc64_table[s - 1][b];
+
+			for (size_t i = 0; i < 8; ++i) {
+				if (r & 1)
+					r = (r >> 1) ^ poly64;
+				else
+					r >>= 1;
+			}
+
+			lzma_crc64_table[s][b] = r;
+		}
+	}
+}
+
+ * The prototype of the CRC64 function:
+ * extern uint64_t lzma_crc64(const uint8_t *buf, size_t size, uint64_t crc);
+ */
+
+/*
+ * On some systems, the functions need to be prefixed. The prefix is
+ * usually an underscore.
+ */
+#ifndef __USER_LABEL_PREFIX__
+#	define __USER_LABEL_PREFIX__
+#endif
+#define MAKE_SYM_CAT(prefix, sym) prefix ## sym
+#define MAKE_SYM(prefix, sym) MAKE_SYM_CAT(prefix, sym)
+#define LZMA_CRC64 MAKE_SYM(__USER_LABEL_PREFIX__, lzma_crc64)
+#define LZMA_CRC64_TABLE MAKE_SYM(__USER_LABEL_PREFIX__, lzma_crc64_table)
+
+/*
+ * Solaris assembler doesn't have .p2align, and Darwin uses .align
+ * differently than GNU/Linux and Solaris.
+ */
+#if defined(__APPLE__) || defined(__MSDOS__)
+#	define ALIGN(pow2, abs) .align pow2
+#else
+#	define ALIGN(pow2, abs) .align abs
+#endif
+
+	.text
+	.globl	LZMA_CRC64
+
+#if !defined(__APPLE__) && !defined(_WIN32) && !defined(__CYGWIN__) \
+		&& !defined(__MSDOS__)
+	.type	LZMA_CRC64, @function
+#endif
+
+	ALIGN(4, 16)
+LZMA_CRC64:
+	/*
+	 * Register usage:
+	 * %eax crc LSB
+	 * %edx crc MSB
+	 * %esi buf
+	 * %edi size or buf + size
+	 * %ebx lzma_crc64_table
+	 * %ebp Table index
+	 * %ecx Temporary
+	 */
+	pushl	%ebx
+	pushl	%esi
+	pushl	%edi
+	pushl	%ebp
+	movl	0x14(%esp), %esi /* buf */
+	movl	0x18(%esp), %edi /* size */
+	movl	0x1C(%esp), %eax /* crc LSB */
+	movl	0x20(%esp), %edx /* crc MSB */
+
+	/*
+	 * Store the address of lzma_crc64_table to %ebx. This is needed to
+	 * get position-independent code (PIC).
+	 *
+	 * The PIC macro is defined by libtool, while __PIC__ is defined
+	 * by GCC but only on some systems. Testing for both makes it simpler
+	 * to test this code without libtool, and keeps the code working also
+	 * when built with libtool but using something else than GCC.
+	 *
+	 * I understood that libtool may define PIC on Windows even though
+	 * the code in Windows DLLs is not PIC in sense that it is in ELF
+	 * binaries, so we need a separate check to always use the non-PIC
+	 * code on Windows.
+	 */
+#if (!defined(PIC) && !defined(__PIC__)) \
+		|| (defined(_WIN32) || defined(__CYGWIN__))
+	/* Not PIC */
+	movl	$ LZMA_CRC64_TABLE, %ebx
+#elif defined(__APPLE__)
+	/* Mach-O */
+	call	.L_get_pc
+.L_pic:
+	leal	.L_lzma_crc64_table$non_lazy_ptr-.L_pic(%ebx), %ebx
+	movl	(%ebx), %ebx
+#else
+	/* ELF */
+	call	.L_get_pc
+	addl	$_GLOBAL_OFFSET_TABLE_, %ebx
+	movl	LZMA_CRC64_TABLE@GOT(%ebx), %ebx
+#endif
+
+	/* Complement the initial value. */
+	notl	%eax
+	notl	%edx
+
+.L_align:
+	/*
+	 * Check if there is enough input to use slicing-by-four.
+	 * We need eight bytes, because the loop pre-reads four bytes.
+	 */
+	cmpl	$8, %edi
+	jb	.L_rest
+
+	/* Check if we have reached alignment of four bytes. */
+	testl	$3, %esi
+	jz	.L_slice
+
+	/* Calculate CRC of the next input byte. */
+	movzbl	(%esi), %ebp
+	incl	%esi
+	movzbl	%al, %ecx
+	xorl	%ecx, %ebp
+	shrdl	$8, %edx, %eax
+	xorl	(%ebx, %ebp, 8), %eax
+	shrl	$8, %edx
+	xorl	4(%ebx, %ebp, 8), %edx
+	decl	%edi
+	jmp	.L_align
+
+.L_slice:
+	/*
+	 * If we get here, there's at least eight bytes of aligned input
+	 * available. Make %edi multiple of four bytes. Store the possible
+	 * remainder over the "size" variable in the argument stack.
+	 */
+	movl	%edi, 0x18(%esp)
+	andl	$-4, %edi
+	subl	%edi, 0x18(%esp)
+
+	/*
+	 * Let %edi be buf + size - 4 while running the main loop. This way
+	 * we can compare for equality to determine when exit the loop.
+	 */
+	addl	%esi, %edi
+	subl	$4, %edi
+
+	/* Read in the first four aligned bytes. */
+	movl	(%esi), %ecx
+
+.L_loop:
+	xorl	%eax, %ecx
+	movzbl	%cl, %ebp
+	movl	0x1800(%ebx, %ebp, 8), %eax
+	xorl	%edx, %eax
+	movl	0x1804(%ebx, %ebp, 8), %edx
+	movzbl	%ch, %ebp
+	xorl	0x1000(%ebx, %ebp, 8), %eax
+	xorl	0x1004(%ebx, %ebp, 8), %edx
+	shrl	$16, %ecx
+	movzbl	%cl, %ebp
+	xorl	0x0800(%ebx, %ebp, 8), %eax
+	xorl	0x0804(%ebx, %ebp, 8), %edx
+	movzbl	%ch, %ebp
+	addl	$4, %esi
+	xorl	(%ebx, %ebp, 8), %eax
+	xorl	4(%ebx, %ebp, 8), %edx
+
+	/* Check for end of aligned input. */
+	cmpl	%edi, %esi
+
+	/*
+	 * Copy the next input byte to %ecx. It is slightly faster to
+	 * read it here than at the top of the loop.
+	 */
+	movl	(%esi), %ecx
+	jb	.L_loop
+
+	/*
+	 * Process the remaining four bytes, which we have already
+	 * copied to %ecx.
+	 */
+	xorl	%eax, %ecx
+	movzbl	%cl, %ebp
+	movl	0x1800(%ebx, %ebp, 8), %eax
+	xorl	%edx, %eax
+	movl	0x1804(%ebx, %ebp, 8), %edx
+	movzbl	%ch, %ebp
+	xorl	0x1000(%ebx, %ebp, 8), %eax
+	xorl	0x1004(%ebx, %ebp, 8), %edx
+	shrl	$16, %ecx
+	movzbl	%cl, %ebp
+	xorl	0x0800(%ebx, %ebp, 8), %eax
+	xorl	0x0804(%ebx, %ebp, 8), %edx
+	movzbl	%ch, %ebp
+	addl	$4, %esi
+	xorl	(%ebx, %ebp, 8), %eax
+	xorl	4(%ebx, %ebp, 8), %edx
+
+	/* Copy the number of remaining bytes to %edi. */
+	movl	0x18(%esp), %edi
+
+.L_rest:
+	/* Check for end of input. */
+	testl	%edi, %edi
+	jz	.L_return
+
+	/* Calculate CRC of the next input byte. */
+	movzbl	(%esi), %ebp
+	incl	%esi
+	movzbl	%al, %ecx
+	xorl	%ecx, %ebp
+	shrdl	$8, %edx, %eax
+	xorl	(%ebx, %ebp, 8), %eax
+	shrl	$8, %edx
+	xorl	4(%ebx, %ebp, 8), %edx
+	decl	%edi
+	jmp	.L_rest
+
+.L_return:
+	/* Complement the final value. */
+	notl	%eax
+	notl	%edx
+
+	popl	%ebp
+	popl	%edi
+	popl	%esi
+	popl	%ebx
+	ret
+
+#if defined(PIC) || defined(__PIC__)
+	ALIGN(4, 16)
+.L_get_pc:
+	movl	(%esp), %ebx
+	ret
+#endif
+
+#if defined(__APPLE__) && (defined(PIC) || defined(__PIC__))
+	/* Mach-O PIC */
+	.section __IMPORT,__pointers,non_lazy_symbol_pointers
+.L_lzma_crc64_table$non_lazy_ptr:
+	.indirect_symbol LZMA_CRC64_TABLE
+	.long 0
+
+#elif defined(_WIN32) || defined(__CYGWIN__)
+#	ifdef DLL_EXPORT
+	/* This is equivalent of __declspec(dllexport). */
+	.section .drectve
+	.ascii " -export:lzma_crc64"
+#	endif
+
+#elif !defined(__MSDOS__)
+	/* ELF */
+	.size	LZMA_CRC64, .-LZMA_CRC64
+#endif
+
+/*
+ * This is needed to support non-executable stack. It's ugly to
+ * use __linux__ here, but I don't know a way to detect when
+ * we are using GNU assembler.
+ */
+#if defined(__ELF__) && defined(__linux__)
+	.section	.note.GNU-stack,"",@progbits
+#endif
diff --git a/Utilities/cmliblzma/liblzma/check/crc_macros.h b/Utilities/cmliblzma/liblzma/check/crc_macros.h
new file mode 100644
index 0000000..a7c21b7
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/check/crc_macros.h
@@ -0,0 +1,30 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       crc_macros.h
+/// \brief      Some endian-dependent macros for CRC32 and CRC64
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#ifdef WORDS_BIGENDIAN
+#	define A(x) ((x) >> 24)
+#	define B(x) (((x) >> 16) & 0xFF)
+#	define C(x) (((x) >> 8) & 0xFF)
+#	define D(x) ((x) & 0xFF)
+
+#	define S8(x) ((x) << 8)
+#	define S32(x) ((x) << 32)
+
+#else
+#	define A(x) ((x) & 0xFF)
+#	define B(x) (((x) >> 8) & 0xFF)
+#	define C(x) (((x) >> 16) & 0xFF)
+#	define D(x) ((x) >> 24)
+
+#	define S8(x) ((x) >> 8)
+#	define S32(x) ((x) >> 32)
+#endif
diff --git a/Utilities/cmliblzma/liblzma/check/sha256.c b/Utilities/cmliblzma/liblzma/check/sha256.c
new file mode 100644
index 0000000..c2c85eb
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/check/sha256.c
@@ -0,0 +1,204 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       sha256.c
+/// \brief      SHA-256
+///
+/// \todo       Crypto++ has x86 ASM optimizations. They use SSE so if they
+///             are imported to liblzma, SSE instructions need to be used
+///             conditionally to keep the code working on older boxes.
+//
+//  This code is based on the code found from 7-Zip, which has a modified
+//  version of the SHA-256 found from Crypto++ <http://www.cryptopp.com/>.
+//  The code was modified a little to fit into liblzma.
+//
+//  Authors:    Kevin Springle
+//              Wei Dai
+//              Igor Pavlov
+//              Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+// Avoid bogus warnings in transform().
+#if (__GNUC__ == 4 && __GNUC_MINOR__ >= 2) || __GNUC__ > 4
+#	pragma GCC diagnostic ignored "-Wuninitialized"
+#endif
+
+#include "check.h"
+
+// At least on x86, GCC is able to optimize this to a rotate instruction.
+#define rotr_32(num, amount) ((num) >> (amount) | (num) << (32 - (amount)))
+
+#define blk0(i) (W[i] = data[i])
+#define blk2(i) (W[i & 15] += s1(W[(i - 2) & 15]) + W[(i - 7) & 15] \
+		+ s0(W[(i - 15) & 15]))
+
+#define Ch(x, y, z) (z ^ (x & (y ^ z)))
+#define Maj(x, y, z) ((x & y) | (z & (x | y)))
+
+#define a(i) T[(0 - i) & 7]
+#define b(i) T[(1 - i) & 7]
+#define c(i) T[(2 - i) & 7]
+#define d(i) T[(3 - i) & 7]
+#define e(i) T[(4 - i) & 7]
+#define f(i) T[(5 - i) & 7]
+#define g(i) T[(6 - i) & 7]
+#define h(i) T[(7 - i) & 7]
+
+#define R(i) \
+	h(i) += S1(e(i)) + Ch(e(i), f(i), g(i)) + SHA256_K[i + j] \
+		+ (j ? blk2(i) : blk0(i)); \
+	d(i) += h(i); \
+	h(i) += S0(a(i)) + Maj(a(i), b(i), c(i))
+
+#define S0(x) (rotr_32(x, 2) ^ rotr_32(x, 13) ^ rotr_32(x, 22))
+#define S1(x) (rotr_32(x, 6) ^ rotr_32(x, 11) ^ rotr_32(x, 25))
+#define s0(x) (rotr_32(x, 7) ^ rotr_32(x, 18) ^ (x >> 3))
+#define s1(x) (rotr_32(x, 17) ^ rotr_32(x, 19) ^ (x >> 10))
+
+
+static const uint32_t SHA256_K[64] = {
+	0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5,
+	0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5,
+	0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3,
+	0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174,
+	0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC,
+	0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA,
+	0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7,
+	0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967,
+	0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13,
+	0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85,
+	0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3,
+	0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070,
+	0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5,
+	0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3,
+	0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208,
+	0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2,
+};
+
+
+static void
+transform(uint32_t state[], const uint32_t data[])
+{
+	uint32_t W[16];
+	uint32_t T[8];
+	unsigned int j;
+
+	// Copy state[] to working vars.
+	memcpy(T, state, sizeof(T));
+
+	// 64 operations, partially loop unrolled
+	for (j = 0; j < 64; j += 16) {
+		R( 0); R( 1); R( 2); R( 3);
+		R( 4); R( 5); R( 6); R( 7);
+		R( 8); R( 9); R(10); R(11);
+		R(12); R(13); R(14); R(15);
+	}
+
+	// Add the working vars back into state[].
+	state[0] += a(0);
+	state[1] += b(0);
+	state[2] += c(0);
+	state[3] += d(0);
+	state[4] += e(0);
+	state[5] += f(0);
+	state[6] += g(0);
+	state[7] += h(0);
+}
+
+
+static void
+process(lzma_check_state *check)
+{
+#ifdef WORDS_BIGENDIAN
+	transform(check->state.sha256.state, check->buffer.u32);
+
+#else
+	uint32_t data[16];
+	size_t i;
+
+	for (i = 0; i < 16; ++i)
+		data[i] = bswap32(check->buffer.u32[i]);
+
+	transform(check->state.sha256.state, data);
+#endif
+
+	return;
+}
+
+
+extern void
+lzma_sha256_init(lzma_check_state *check)
+{
+	static const uint32_t s[8] = {
+		0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A,
+		0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19,
+	};
+
+	memcpy(check->state.sha256.state, s, sizeof(s));
+	check->state.sha256.size = 0;
+
+	return;
+}
+
+
+extern void
+lzma_sha256_update(const uint8_t *buf, size_t size, lzma_check_state *check)
+{
+	// Copy the input data into a properly aligned temporary buffer.
+	// This way we can be called with arbitrarily sized buffers
+	// (no need to be multiple of 64 bytes), and the code works also
+	// on architectures that don't allow unaligned memory access.
+	while (size > 0) {
+		const size_t copy_start = check->state.sha256.size & 0x3F;
+		size_t copy_size = 64 - copy_start;
+		if (copy_size > size)
+			copy_size = size;
+
+		memcpy(check->buffer.u8 + copy_start, buf, copy_size);
+
+		buf += copy_size;
+		size -= copy_size;
+		check->state.sha256.size += copy_size;
+
+		if ((check->state.sha256.size & 0x3F) == 0)
+			process(check);
+	}
+
+	return;
+}
+
+
+extern void
+lzma_sha256_finish(lzma_check_state *check)
+{
+	size_t i;
+
+	// Add padding as described in RFC 3174 (it describes SHA-1 but
+	// the same padding style is used for SHA-256 too).
+	size_t pos = check->state.sha256.size & 0x3F;
+	check->buffer.u8[pos++] = 0x80;
+
+	while (pos != 64 - 8) {
+		if (pos == 64) {
+			process(check);
+			pos = 0;
+		}
+
+		check->buffer.u8[pos++] = 0x00;
+	}
+
+	// Convert the message size from bytes to bits.
+	check->state.sha256.size *= 8;
+
+	check->buffer.u64[(64 - 8) / 8] = conv64be(check->state.sha256.size);
+
+	process(check);
+
+	for (i = 0; i < 8; ++i)
+		check->buffer.u32[i] = conv32be(check->state.sha256.state[i]);
+
+	return;
+}
diff --git a/Utilities/cmliblzma/liblzma/common/alone_decoder.c b/Utilities/cmliblzma/liblzma/common/alone_decoder.c
new file mode 100644
index 0000000..5f5e564
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/alone_decoder.c
@@ -0,0 +1,236 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       alone_decoder.c
+/// \brief      Decoder for LZMA_Alone files
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "alone_decoder.h"
+#include "lzma_decoder.h"
+#include "lz_decoder.h"
+
+
+struct lzma_coder_s {
+	lzma_next_coder next;
+
+	enum {
+		SEQ_PROPERTIES,
+		SEQ_DICTIONARY_SIZE,
+		SEQ_UNCOMPRESSED_SIZE,
+		SEQ_CODER_INIT,
+		SEQ_CODE,
+	} sequence;
+
+	/// If true, reject files that are unlikely to be .lzma files.
+	/// If false, more non-.lzma files get accepted and will give
+	/// LZMA_DATA_ERROR either immediately or after a few output bytes.
+	bool picky;
+
+	/// Position in the header fields
+	size_t pos;
+
+	/// Uncompressed size decoded from the header
+	lzma_vli uncompressed_size;
+
+	/// Memory usage limit
+	uint64_t memlimit;
+
+	/// Amount of memory actually needed (only an estimate)
+	uint64_t memusage;
+
+	/// Options decoded from the header needed to initialize
+	/// the LZMA decoder
+	lzma_options_lzma options;
+};
+
+
+static lzma_ret
+alone_decode(lzma_coder *coder,
+		lzma_allocator *allocator lzma_attribute((__unused__)),
+		const uint8_t *LZMA_RESTRICT in, size_t *LZMA_RESTRICT in_pos,
+		size_t in_size, uint8_t *LZMA_RESTRICT out,
+		size_t *LZMA_RESTRICT out_pos, size_t out_size,
+		lzma_action action)
+{
+	while (*out_pos < out_size
+			&& (coder->sequence == SEQ_CODE || *in_pos < in_size))
+	switch (coder->sequence) {
+	case SEQ_PROPERTIES:
+		if (lzma_lzma_lclppb_decode(&coder->options, in[*in_pos]))
+			return LZMA_FORMAT_ERROR;
+
+		coder->sequence = SEQ_DICTIONARY_SIZE;
+		++*in_pos;
+		break;
+
+	case SEQ_DICTIONARY_SIZE:
+		coder->options.dict_size
+				|= (size_t)(in[*in_pos]) << (coder->pos * 8);
+
+		if (++coder->pos == 4) {
+			if (coder->picky && coder->options.dict_size
+					!= UINT32_MAX) {
+				// A hack to ditch tons of false positives:
+				// We allow only dictionary sizes that are
+				// 2^n or 2^n + 2^(n-1). LZMA_Alone created
+				// only files with 2^n, but accepts any
+				// dictionary size.
+				uint32_t d = coder->options.dict_size - 1;
+				d |= d >> 2;
+				d |= d >> 3;
+				d |= d >> 4;
+				d |= d >> 8;
+				d |= d >> 16;
+				++d;
+
+				if (d != coder->options.dict_size)
+					return LZMA_FORMAT_ERROR;
+			}
+
+			coder->pos = 0;
+			coder->sequence = SEQ_UNCOMPRESSED_SIZE;
+		}
+
+		++*in_pos;
+		break;
+
+	case SEQ_UNCOMPRESSED_SIZE:
+		coder->uncompressed_size
+				|= (lzma_vli)(in[*in_pos]) << (coder->pos * 8);
+		++*in_pos;
+		if (++coder->pos < 8)
+			break;
+
+		// Another hack to ditch false positives: Assume that
+		// if the uncompressed size is known, it must be less
+		// than 256 GiB.
+		if (coder->picky
+				&& coder->uncompressed_size != LZMA_VLI_UNKNOWN
+				&& coder->uncompressed_size
+					>= (LZMA_VLI_C(1) << 38))
+			return LZMA_FORMAT_ERROR;
+
+		// Calculate the memory usage so that it is ready
+		// for SEQ_CODER_INIT.
+		coder->memusage = lzma_lzma_decoder_memusage(&coder->options)
+				+ LZMA_MEMUSAGE_BASE;
+
+		coder->pos = 0;
+		coder->sequence = SEQ_CODER_INIT;
+
+	// Fall through
+
+	case SEQ_CODER_INIT: {
+		lzma_ret ret;
+
+		lzma_filter_info filters[2] = {
+			{ 0, &lzma_lzma_decoder_init, &coder->options },
+			{ 0, NULL, NULL }
+		};
+
+		if (coder->memusage > coder->memlimit)
+			return LZMA_MEMLIMIT_ERROR;
+
+		ret = lzma_next_filter_init(&coder->next,
+				allocator, filters);
+		if (ret != LZMA_OK)
+			return ret;
+
+		// Use a hack to set the uncompressed size.
+		lzma_lz_decoder_uncompressed(coder->next.coder,
+				coder->uncompressed_size);
+
+		coder->sequence = SEQ_CODE;
+		break;
+	}
+
+	case SEQ_CODE: {
+		return coder->next.code(coder->next.coder,
+				allocator, in, in_pos, in_size,
+				out, out_pos, out_size, action);
+	}
+
+	default:
+		return LZMA_PROG_ERROR;
+	}
+
+	return LZMA_OK;
+}
+
+
+static void
+alone_decoder_end(lzma_coder *coder, lzma_allocator *allocator)
+{
+	lzma_next_end(&coder->next, allocator);
+	lzma_free(coder, allocator);
+	return;
+}
+
+
+static lzma_ret
+alone_decoder_memconfig(lzma_coder *coder, uint64_t *memusage,
+		uint64_t *old_memlimit, uint64_t new_memlimit)
+{
+	*memusage = coder->memusage;
+	*old_memlimit = coder->memlimit;
+
+	if (new_memlimit != 0) {
+		if (new_memlimit < coder->memusage)
+			return LZMA_MEMLIMIT_ERROR;
+
+		coder->memlimit = new_memlimit;
+	}
+
+	return LZMA_OK;
+}
+
+
+extern lzma_ret
+lzma_alone_decoder_init(lzma_next_coder *next, lzma_allocator *allocator,
+		uint64_t memlimit, bool picky)
+{
+	lzma_next_coder_init(&lzma_alone_decoder_init, next, allocator);
+
+	if (memlimit == 0)
+		return LZMA_PROG_ERROR;
+
+	if (next->coder == NULL) {
+		next->coder = lzma_alloc(sizeof(lzma_coder), allocator);
+		if (next->coder == NULL)
+			return LZMA_MEM_ERROR;
+
+		next->code = &alone_decode;
+		next->end = &alone_decoder_end;
+		next->memconfig = &alone_decoder_memconfig;
+		next->coder->next = LZMA_NEXT_CODER_INIT;
+	}
+
+	next->coder->sequence = SEQ_PROPERTIES;
+	next->coder->picky = picky;
+	next->coder->pos = 0;
+	next->coder->options.dict_size = 0;
+	next->coder->options.preset_dict = NULL;
+	next->coder->options.preset_dict_size = 0;
+	next->coder->uncompressed_size = 0;
+	next->coder->memlimit = memlimit;
+	next->coder->memusage = LZMA_MEMUSAGE_BASE;
+
+	return LZMA_OK;
+}
+
+
+extern LZMA_API(lzma_ret)
+lzma_alone_decoder(lzma_stream *strm, uint64_t memlimit)
+{
+	lzma_next_strm_init2(lzma_alone_decoder_init, strm, memlimit, false);
+
+	strm->internal->supported_actions[LZMA_RUN] = true;
+	strm->internal->supported_actions[LZMA_FINISH] = true;
+
+	return LZMA_OK;
+}
diff --git a/Utilities/cmliblzma/liblzma/common/alone_decoder.h b/Utilities/cmliblzma/liblzma/common/alone_decoder.h
new file mode 100644
index 0000000..f666fc3
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/alone_decoder.h
@@ -0,0 +1,23 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       alone_decoder.h
+/// \brief      Decoder for LZMA_Alone files
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#ifndef LZMA_ALONE_DECODER_H
+#define LZMA_ALONE_DECODER_H
+
+#include "common.h"
+
+
+extern lzma_ret lzma_alone_decoder_init(
+		lzma_next_coder *next, lzma_allocator *allocator,
+		uint64_t memlimit, bool picky);
+
+#endif
diff --git a/Utilities/cmliblzma/liblzma/common/alone_encoder.c b/Utilities/cmliblzma/liblzma/common/alone_encoder.c
new file mode 100644
index 0000000..4207b4a
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/alone_encoder.c
@@ -0,0 +1,155 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       alone_decoder.c
+/// \brief      Decoder for LZMA_Alone files
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "common.h"
+#include "lzma_encoder.h"
+
+
+#define ALONE_HEADER_SIZE (1 + 4 + 8)
+
+
+struct lzma_coder_s {
+	lzma_next_coder next;
+
+	enum {
+		SEQ_HEADER,
+		SEQ_CODE,
+	} sequence;
+
+	size_t header_pos;
+	uint8_t header[ALONE_HEADER_SIZE];
+};
+
+
+static lzma_ret
+alone_encode(lzma_coder *coder,
+		lzma_allocator *allocator lzma_attribute((__unused__)),
+		const uint8_t *LZMA_RESTRICT in, size_t *LZMA_RESTRICT in_pos,
+		size_t in_size, uint8_t *LZMA_RESTRICT out,
+		size_t *LZMA_RESTRICT out_pos, size_t out_size,
+		lzma_action action)
+{
+	while (*out_pos < out_size)
+	switch (coder->sequence) {
+	case SEQ_HEADER:
+		lzma_bufcpy(coder->header, &coder->header_pos,
+				ALONE_HEADER_SIZE,
+				out, out_pos, out_size);
+		if (coder->header_pos < ALONE_HEADER_SIZE)
+			return LZMA_OK;
+
+		coder->sequence = SEQ_CODE;
+		break;
+
+	case SEQ_CODE:
+		return coder->next.code(coder->next.coder,
+				allocator, in, in_pos, in_size,
+				out, out_pos, out_size, action);
+
+	default:
+		assert(0);
+		return LZMA_PROG_ERROR;
+	}
+
+	return LZMA_OK;
+}
+
+
+static void
+alone_encoder_end(lzma_coder *coder, lzma_allocator *allocator)
+{
+	lzma_next_end(&coder->next, allocator);
+	lzma_free(coder, allocator);
+	return;
+}
+
+
+// At least for now, this is not used by any internal function.
+static lzma_ret
+alone_encoder_init(lzma_next_coder *next, lzma_allocator *allocator,
+		const lzma_options_lzma *options)
+{
+	uint32_t d;
+
+	// Initialize the LZMA encoder.
+	const lzma_filter_info filters[2] = {
+	    { 0, &lzma_lzma_encoder_init, (void *)(options) },
+	    { 0, NULL, NULL }
+	};
+
+	lzma_next_coder_init(&alone_encoder_init, next, allocator);
+
+	if (next->coder == NULL) {
+		next->coder = lzma_alloc(sizeof(lzma_coder), allocator);
+		if (next->coder == NULL)
+			return LZMA_MEM_ERROR;
+
+		next->code = &alone_encode;
+		next->end = &alone_encoder_end;
+		next->coder->next = LZMA_NEXT_CODER_INIT;
+	}
+
+	// Basic initializations
+	next->coder->sequence = SEQ_HEADER;
+	next->coder->header_pos = 0;
+
+	// Encode the header:
+	// - Properties (1 byte)
+	if (lzma_lzma_lclppb_encode(options, next->coder->header))
+		return LZMA_OPTIONS_ERROR;
+
+	// - Dictionary size (4 bytes)
+	if (options->dict_size < LZMA_DICT_SIZE_MIN)
+		return LZMA_OPTIONS_ERROR;
+
+	// Round up to the next 2^n or 2^n + 2^(n - 1) depending on which
+	// one is the next unless it is UINT32_MAX. While the header would
+	// allow any 32-bit integer, we do this to keep the decoder of liblzma
+	// accepting the resulting files.
+	d = options->dict_size - 1;
+	d |= d >> 2;
+	d |= d >> 3;
+	d |= d >> 4;
+	d |= d >> 8;
+	d |= d >> 16;
+	if (d != UINT32_MAX)
+		++d;
+
+	unaligned_write32le(next->coder->header + 1, d);
+
+	// - Uncompressed size (always unknown and using EOPM)
+	memset(next->coder->header + 1 + 4, 0xFF, 8);
+
+	return lzma_next_filter_init(&next->coder->next, allocator, filters);
+}
+
+
+/*
+extern lzma_ret
+lzma_alone_encoder_init(lzma_next_coder *next, lzma_allocator *allocator,
+		const lzma_options_alone *options)
+{
+	lzma_next_coder_init(&alone_encoder_init, next, allocator, options);
+}
+*/
+
+
+extern LZMA_API(lzma_ret)
+lzma_alone_encoder(lzma_stream *strm, const lzma_options_lzma *options)
+{
+	lzma_next_strm_init1(alone_encoder_init, strm, options);
+
+	strm->internal->supported_actions[LZMA_RUN] = true;
+	strm->internal->supported_actions[LZMA_FINISH] = true;
+
+	return LZMA_OK;
+}
diff --git a/Utilities/cmliblzma/liblzma/common/auto_decoder.c b/Utilities/cmliblzma/liblzma/common/auto_decoder.c
new file mode 100644
index 0000000..24cf489
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/auto_decoder.c
@@ -0,0 +1,186 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       auto_decoder.c
+/// \brief      Autodetect between .xz Stream and .lzma (LZMA_Alone) formats
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "stream_decoder.h"
+#include "alone_decoder.h"
+
+
+struct lzma_coder_s {
+	/// Stream decoder or LZMA_Alone decoder
+	lzma_next_coder next;
+
+	uint64_t memlimit;
+	uint32_t flags;
+
+	enum {
+		SEQ_INIT,
+		SEQ_CODE,
+		SEQ_FINISH,
+	} sequence;
+};
+
+
+static lzma_ret
+auto_decode(lzma_coder *coder, lzma_allocator *allocator,
+		const uint8_t *LZMA_RESTRICT in, size_t *LZMA_RESTRICT in_pos,
+		size_t in_size, uint8_t *LZMA_RESTRICT out,
+		size_t *LZMA_RESTRICT out_pos, size_t out_size, lzma_action action)
+{
+	switch (coder->sequence) {
+	case SEQ_INIT:
+		if (*in_pos >= in_size)
+			return LZMA_OK;
+
+		// Update the sequence now, because we want to continue from
+		// SEQ_CODE even if we return some LZMA_*_CHECK.
+		coder->sequence = SEQ_CODE;
+
+		// Detect the file format. For now this is simple, since if
+		// it doesn't start with 0xFD (the first magic byte of the
+		// new format), it has to be LZMA_Alone, or something that
+		// we don't support at all.
+		if (in[*in_pos] == 0xFD) {
+			return_if_error(lzma_stream_decoder_init(
+					&coder->next, allocator,
+					coder->memlimit, coder->flags));
+		} else {
+			return_if_error(lzma_alone_decoder_init(&coder->next,
+					allocator, coder->memlimit, true));
+
+			// If the application wants to know about missing
+			// integrity check or about the check in general, we
+			// need to handle it here, because LZMA_Alone decoder
+			// doesn't accept any flags.
+			if (coder->flags & LZMA_TELL_NO_CHECK)
+				return LZMA_NO_CHECK;
+
+			if (coder->flags & LZMA_TELL_ANY_CHECK)
+				return LZMA_GET_CHECK;
+		}
+
+	// Fall through
+
+	case SEQ_CODE: {
+		const lzma_ret ret = coder->next.code(
+				coder->next.coder, allocator,
+				in, in_pos, in_size,
+				out, out_pos, out_size, action);
+		if (ret != LZMA_STREAM_END
+				|| (coder->flags & LZMA_CONCATENATED) == 0)
+			return ret;
+
+		coder->sequence = SEQ_FINISH;
+	}
+
+	// Fall through
+
+	case SEQ_FINISH:
+		// When LZMA_DECODE_CONCATENATED was used and we were decoding
+		// LZMA_Alone file, we need to check check that there is no
+		// trailing garbage and wait for LZMA_FINISH.
+		if (*in_pos < in_size)
+			return LZMA_DATA_ERROR;
+
+		return action == LZMA_FINISH ? LZMA_STREAM_END : LZMA_OK;
+
+	default:
+		assert(0);
+		return LZMA_PROG_ERROR;
+	}
+}
+
+
+static void
+auto_decoder_end(lzma_coder *coder, lzma_allocator *allocator)
+{
+	lzma_next_end(&coder->next, allocator);
+	lzma_free(coder, allocator);
+	return;
+}
+
+
+static lzma_check
+auto_decoder_get_check(const lzma_coder *coder)
+{
+	// It is LZMA_Alone if get_check is NULL.
+	return coder->next.get_check == NULL ? LZMA_CHECK_NONE
+			: coder->next.get_check(coder->next.coder);
+}
+
+
+static lzma_ret
+auto_decoder_memconfig(lzma_coder *coder, uint64_t *memusage,
+		uint64_t *old_memlimit, uint64_t new_memlimit)
+{
+	lzma_ret ret;
+
+	if (coder->next.memconfig != NULL) {
+		ret = coder->next.memconfig(coder->next.coder,
+				memusage, old_memlimit, new_memlimit);
+		assert(*old_memlimit == coder->memlimit);
+	} else {
+		// No coder is configured yet. Use the base value as
+		// the current memory usage.
+		*memusage = LZMA_MEMUSAGE_BASE;
+		*old_memlimit = coder->memlimit;
+		ret = LZMA_OK;
+	}
+
+	if (ret == LZMA_OK && new_memlimit != 0)
+		coder->memlimit = new_memlimit;
+
+	return ret;
+}
+
+
+static lzma_ret
+auto_decoder_init(lzma_next_coder *next, lzma_allocator *allocator,
+		uint64_t memlimit, uint32_t flags)
+{
+	lzma_next_coder_init(&auto_decoder_init, next, allocator);
+
+	if (memlimit == 0)
+		return LZMA_PROG_ERROR;
+
+	if (flags & ~LZMA_SUPPORTED_FLAGS)
+		return LZMA_OPTIONS_ERROR;
+
+	if (next->coder == NULL) {
+		next->coder = lzma_alloc(sizeof(lzma_coder), allocator);
+		if (next->coder == NULL)
+			return LZMA_MEM_ERROR;
+
+		next->code = &auto_decode;
+		next->end = &auto_decoder_end;
+		next->get_check = &auto_decoder_get_check;
+		next->memconfig = &auto_decoder_memconfig;
+		next->coder->next = LZMA_NEXT_CODER_INIT;
+	}
+
+	next->coder->memlimit = memlimit;
+	next->coder->flags = flags;
+	next->coder->sequence = SEQ_INIT;
+
+	return LZMA_OK;
+}
+
+
+extern LZMA_API(lzma_ret)
+lzma_auto_decoder(lzma_stream *strm, uint64_t memlimit, uint32_t flags)
+{
+	lzma_next_strm_init2(auto_decoder_init, strm, memlimit, flags);
+
+	strm->internal->supported_actions[LZMA_RUN] = true;
+	strm->internal->supported_actions[LZMA_FINISH] = true;
+
+	return LZMA_OK;
+}
diff --git a/Utilities/cmliblzma/liblzma/common/block_buffer_decoder.c b/Utilities/cmliblzma/liblzma/common/block_buffer_decoder.c
new file mode 100644
index 0000000..b4bd388
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/block_buffer_decoder.c
@@ -0,0 +1,82 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       block_buffer_decoder.c
+/// \brief      Single-call .xz Block decoder
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "block_decoder.h"
+
+
+extern LZMA_API(lzma_ret)
+lzma_block_buffer_decode(lzma_block *block, lzma_allocator *allocator,
+		const uint8_t *in, size_t *in_pos, size_t in_size,
+		uint8_t *out, size_t *out_pos, size_t out_size)
+{
+	lzma_next_coder block_decoder;
+	lzma_ret ret;
+
+	if (in_pos == NULL || (in == NULL && *in_pos != in_size)
+			|| *in_pos > in_size || out_pos == NULL
+			|| (out == NULL && *out_pos != out_size)
+			|| *out_pos > out_size)
+		return LZMA_PROG_ERROR;
+
+	// Initialize the Block decoder.
+	block_decoder = LZMA_NEXT_CODER_INIT;
+	ret = lzma_block_decoder_init(&block_decoder, allocator, block);
+
+	if (ret == LZMA_OK) {
+		// Save the positions so that we can restore them in case
+		// an error occurs.
+		const size_t in_start = *in_pos;
+		const size_t out_start = *out_pos;
+
+		// Do the actual decoding.
+		ret = block_decoder.code(block_decoder.coder, allocator,
+				in, in_pos, in_size, out, out_pos, out_size,
+				LZMA_FINISH);
+
+		if (ret == LZMA_STREAM_END) {
+			ret = LZMA_OK;
+		} else {
+			if (ret == LZMA_OK) {
+				// Either the input was truncated or the
+				// output buffer was too small.
+				assert(*in_pos == in_size
+						|| *out_pos == out_size);
+
+				// If all the input was consumed, then the
+				// input is truncated, even if the output
+				// buffer is also full. This is because
+				// processing the last byte of the Block
+				// never produces output.
+				//
+				// NOTE: This assumption may break when new
+				// filters are added, if the end marker of
+				// the filter doesn't consume at least one
+				// complete byte.
+				if (*in_pos == in_size)
+					ret = LZMA_DATA_ERROR;
+				else
+					ret = LZMA_BUF_ERROR;
+			}
+
+			// Restore the positions.
+			*in_pos = in_start;
+			*out_pos = out_start;
+		}
+	}
+
+	// Free the decoder memory. This needs to be done even if
+	// initialization fails, because the internal API doesn't
+	// require the initialization function to free its memory on error.
+	lzma_next_end(&block_decoder, allocator);
+
+	return ret;
+}
diff --git a/Utilities/cmliblzma/liblzma/common/block_buffer_encoder.c b/Utilities/cmliblzma/liblzma/common/block_buffer_encoder.c
new file mode 100644
index 0000000..136f7f5
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/block_buffer_encoder.c
@@ -0,0 +1,315 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       block_buffer_encoder.c
+/// \brief      Single-call .xz Block encoder
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "block_encoder.h"
+#include "filter_encoder.h"
+#include "lzma2_encoder.h"
+#include "check.h"
+
+
+/// Estimate the maximum size of the Block Header and Check fields for
+/// a Block that uses LZMA2 uncompressed chunks. We could use
+/// lzma_block_header_size() but this is simpler.
+///
+/// Block Header Size + Block Flags + Compressed Size
+/// + Uncompressed Size + Filter Flags for LZMA2 + CRC32 + Check
+/// and round up to the next multiple of four to take Header Padding
+/// into account.
+#define HEADERS_BOUND ((1 + 1 + 2 * LZMA_VLI_BYTES_MAX + 3 + 4 \
+		+ LZMA_CHECK_SIZE_MAX + 3) & ~3)
+
+
+static lzma_vli
+lzma2_bound(lzma_vli uncompressed_size)
+{
+	lzma_vli overhead;
+
+	// Prevent integer overflow in overhead calculation.
+	if (uncompressed_size > COMPRESSED_SIZE_MAX)
+		return 0;
+
+	// Calculate the exact overhead of the LZMA2 headers: Round
+	// uncompressed_size up to the next multiple of LZMA2_CHUNK_MAX,
+	// multiply by the size of per-chunk header, and add one byte for
+	// the end marker.
+	overhead = ((uncompressed_size + LZMA2_CHUNK_MAX - 1)
+				/ LZMA2_CHUNK_MAX)
+			* LZMA2_HEADER_UNCOMPRESSED + 1;
+
+	// Catch the possible integer overflow.
+	if (COMPRESSED_SIZE_MAX - overhead < uncompressed_size)
+		return 0;
+
+	return uncompressed_size + overhead;
+}
+
+
+extern LZMA_API(size_t)
+lzma_block_buffer_bound(size_t uncompressed_size)
+{
+	// For now, if the data doesn't compress, we always use uncompressed
+	// chunks of LZMA2. In future we may use Subblock filter too, but
+	// but for simplicity we probably will still use the same bound
+	// calculation even though Subblock filter would have slightly less
+	// overhead.
+	lzma_vli lzma2_size = lzma2_bound(uncompressed_size);
+	if (lzma2_size == 0)
+		return 0;
+
+	// Take Block Padding into account.
+	lzma2_size = (lzma2_size + 3) & ~LZMA_VLI_C(3);
+
+#if SIZE_MAX < LZMA_VLI_MAX
+	// Catch the possible integer overflow on 32-bit systems. There's no
+	// overflow on 64-bit systems, because lzma2_bound() already takes
+	// into account the size of the headers in the Block.
+	if (SIZE_MAX - HEADERS_BOUND < lzma2_size)
+		return 0;
+#endif
+
+	return HEADERS_BOUND + lzma2_size;
+}
+
+
+static lzma_ret
+block_encode_uncompressed(lzma_block *block, const uint8_t *in, size_t in_size,
+		uint8_t *out, size_t *out_pos, size_t out_size)
+{
+	size_t in_pos = 0;
+	uint8_t control = 0x01; // Dictionary reset
+	lzma_filter *filters_orig;
+
+	// TODO: Figure out if the last filter is LZMA2 or Subblock and use
+	// that filter to encode the uncompressed chunks.
+
+	// Use LZMA2 uncompressed chunks. We wouldn't need a dictionary at
+	// all, but LZMA2 always requires a dictionary, so use the minimum
+	// value to minimize memory usage of the decoder.
+	lzma_options_lzma lzma2 = { LZMA_DICT_SIZE_MIN };
+
+	lzma_filter filters[2];
+	filters[0].id = LZMA_FILTER_LZMA2;
+	filters[0].options = &lzma2;
+	filters[1].id = LZMA_VLI_UNKNOWN;
+
+	// Set the above filter options to *block temporarily so that we can
+	// encode the Block Header.
+	filters_orig = block->filters;
+	block->filters = filters;
+
+	if (lzma_block_header_size(block) != LZMA_OK) {
+		block->filters = filters_orig;
+		return LZMA_PROG_ERROR;
+	}
+
+	// Check that there's enough output space. The caller has already
+	// set block->compressed_size to what lzma2_bound() has returned,
+	// so we can reuse that value. We know that compressed_size is a
+	// known valid VLI and header_size is a small value so their sum
+	// will never overflow.
+	assert(block->compressed_size == lzma2_bound(in_size));
+	if (out_size - *out_pos
+			< block->header_size + block->compressed_size) {
+		block->filters = filters_orig;
+		return LZMA_BUF_ERROR;
+	}
+
+	if (lzma_block_header_encode(block, out + *out_pos) != LZMA_OK) {
+		block->filters = filters_orig;
+		return LZMA_PROG_ERROR;
+	}
+
+	block->filters = filters_orig;
+	*out_pos += block->header_size;
+
+	// Encode the data using LZMA2 uncompressed chunks.
+
+	while (in_pos < in_size) {
+		size_t copy_size;
+
+		// Control byte: Indicate uncompressed chunk, of which
+		// the first resets the dictionary.
+		out[(*out_pos)++] = control;
+		control = 0x02; // No dictionary reset
+
+		// Size of the uncompressed chunk
+		copy_size = my_min(in_size - in_pos, LZMA2_CHUNK_MAX);
+		out[(*out_pos)++] = (copy_size - 1) >> 8;
+		out[(*out_pos)++] = (copy_size - 1) & 0xFF;
+
+		// The actual data
+		assert(*out_pos + copy_size <= out_size);
+		memcpy(out + *out_pos, in + in_pos, copy_size);
+
+		in_pos += copy_size;
+		*out_pos += copy_size;
+	}
+
+	// End marker
+	out[(*out_pos)++] = 0x00;
+	assert(*out_pos <= out_size);
+
+	return LZMA_OK;
+}
+
+
+static lzma_ret
+block_encode_normal(lzma_block *block, lzma_allocator *allocator,
+		const uint8_t *in, size_t in_size,
+		uint8_t *out, size_t *out_pos, size_t out_size)
+{
+	size_t out_start;
+	lzma_next_coder raw_encoder = LZMA_NEXT_CODER_INIT;
+	lzma_ret ret;
+
+	// Find out the size of the Block Header.
+	block->compressed_size = lzma2_bound(in_size);
+	if (block->compressed_size == 0)
+		return LZMA_DATA_ERROR;
+
+	block->uncompressed_size = in_size;
+	return_if_error(lzma_block_header_size(block));
+
+	// Reserve space for the Block Header and skip it for now.
+	if (out_size - *out_pos <= block->header_size)
+		return LZMA_BUF_ERROR;
+
+	out_start = *out_pos;
+	*out_pos += block->header_size;
+
+	// Limit out_size so that we stop encoding if the output would grow
+	// bigger than what uncompressed Block would be.
+	if (out_size - *out_pos > block->compressed_size)
+		out_size = *out_pos + block->compressed_size;
+
+	// TODO: In many common cases this could be optimized to use
+	// significantly less memory.
+	ret = lzma_raw_encoder_init(
+			&raw_encoder, allocator, block->filters);
+
+	if (ret == LZMA_OK) {
+		size_t in_pos = 0;
+		ret = raw_encoder.code(raw_encoder.coder, allocator,
+				in, &in_pos, in_size, out, out_pos, out_size,
+				LZMA_FINISH);
+	}
+
+	// NOTE: This needs to be run even if lzma_raw_encoder_init() failed.
+	lzma_next_end(&raw_encoder, allocator);
+
+	if (ret == LZMA_STREAM_END) {
+		// Compression was successful. Write the Block Header.
+		block->compressed_size
+				= *out_pos - (out_start + block->header_size);
+		ret = lzma_block_header_encode(block, out + out_start);
+		if (ret != LZMA_OK)
+			ret = LZMA_PROG_ERROR;
+
+	} else if (ret == LZMA_OK) {
+		// Output buffer became full.
+		ret = LZMA_BUF_ERROR;
+	}
+
+	// Reset *out_pos if something went wrong.
+	if (ret != LZMA_OK)
+		*out_pos = out_start;
+
+	return ret;
+}
+
+
+extern LZMA_API(lzma_ret)
+lzma_block_buffer_encode(lzma_block *block, lzma_allocator *allocator,
+		const uint8_t *in, size_t in_size,
+		uint8_t *out, size_t *out_pos, size_t out_size)
+{
+	size_t check_size;
+	lzma_ret ret;
+	size_t i;
+
+	// Validate the arguments.
+	if (block == NULL || (in == NULL && in_size != 0) || out == NULL
+			|| out_pos == NULL || *out_pos > out_size)
+		return LZMA_PROG_ERROR;
+
+	// The contents of the structure may depend on the version so
+	// check the version before validating the contents of *block.
+	if (block->version != 0)
+		return LZMA_OPTIONS_ERROR;
+
+	if ((unsigned int)(block->check) > LZMA_CHECK_ID_MAX
+			|| block->filters == NULL)
+		return LZMA_PROG_ERROR;
+
+	if (!lzma_check_is_supported(block->check))
+		return LZMA_UNSUPPORTED_CHECK;
+
+	// Size of a Block has to be a multiple of four, so limit the size
+	// here already. This way we don't need to check it again when adding
+	// Block Padding.
+	out_size -= (out_size - *out_pos) & 3;
+
+	// Get the size of the Check field.
+	check_size = lzma_check_size(block->check);
+	assert(check_size != UINT32_MAX);
+
+	// Reserve space for the Check field.
+	if (out_size - *out_pos <= check_size)
+		return LZMA_BUF_ERROR;
+
+	out_size -= check_size;
+
+	// Do the actual compression.
+	ret = block_encode_normal(block, allocator,
+			in, in_size, out, out_pos, out_size);
+	if (ret != LZMA_OK) {
+		// If the error was something else than output buffer
+		// becoming full, return the error now.
+		if (ret != LZMA_BUF_ERROR)
+			return ret;
+
+		// The data was uncompressible (at least with the options
+		// given to us) or the output buffer was too small. Use the
+		// uncompressed chunks of LZMA2 to wrap the data into a valid
+		// Block. If we haven't been given enough output space, even
+		// this may fail.
+		return_if_error(block_encode_uncompressed(block, in, in_size,
+				out, out_pos, out_size));
+	}
+
+	assert(*out_pos <= out_size);
+
+	// Block Padding. No buffer overflow here, because we already adjusted
+	// out_size so that (out_size - out_start) is a multiple of four.
+	// Thus, if the buffer is full, the loop body can never run.
+	for (i = (size_t)(block->compressed_size); i & 3; ++i) {
+		assert(*out_pos < out_size);
+		out[(*out_pos)++] = 0x00;
+	}
+
+	// If there's no Check field, we are done now.
+	if (check_size > 0) {
+		// Calculate the integrity check. We reserved space for
+		// the Check field earlier so we don't need to check for
+		// available output space here.
+		lzma_check_state check;
+		lzma_check_init(&check, block->check);
+		lzma_check_update(&check, block->check, in, in_size);
+		lzma_check_finish(&check, block->check);
+
+		memcpy(block->raw_check, check.buffer.u8, check_size);
+		memcpy(out + *out_pos, check.buffer.u8, check_size);
+		*out_pos += check_size;
+	}
+
+	return LZMA_OK;
+}
diff --git a/Utilities/cmliblzma/liblzma/common/block_decoder.c b/Utilities/cmliblzma/liblzma/common/block_decoder.c
new file mode 100644
index 0000000..35996e7
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/block_decoder.c
@@ -0,0 +1,242 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       block_decoder.c
+/// \brief      Decodes .xz Blocks
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "block_decoder.h"
+#include "filter_decoder.h"
+#include "check.h"
+
+
+struct lzma_coder_s {
+	enum {
+		SEQ_CODE,
+		SEQ_PADDING,
+		SEQ_CHECK,
+	} sequence;
+
+	/// The filters in the chain; initialized with lzma_raw_decoder_init().
+	lzma_next_coder next;
+
+	/// Decoding options; we also write Compressed Size and Uncompressed
+	/// Size back to this structure when the decoding has been finished.
+	lzma_block *block;
+
+	/// Compressed Size calculated while decoding
+	lzma_vli compressed_size;
+
+	/// Uncompressed Size calculated while decoding
+	lzma_vli uncompressed_size;
+
+	/// Maximum allowed Compressed Size; this takes into account the
+	/// size of the Block Header and Check fields when Compressed Size
+	/// is unknown.
+	lzma_vli compressed_limit;
+
+	/// Position when reading the Check field
+	size_t check_pos;
+
+	/// Check of the uncompressed data
+	lzma_check_state check;
+};
+
+
+static inline bool
+update_size(lzma_vli *size, lzma_vli add, lzma_vli limit)
+{
+	if (limit > LZMA_VLI_MAX)
+		limit = LZMA_VLI_MAX;
+
+	if (limit < *size || limit - *size < add)
+		return true;
+
+	*size += add;
+
+	return false;
+}
+
+
+static inline bool
+is_size_valid(lzma_vli size, lzma_vli reference)
+{
+	return reference == LZMA_VLI_UNKNOWN || reference == size;
+}
+
+
+static lzma_ret
+block_decode(lzma_coder *coder, lzma_allocator *allocator,
+		const uint8_t *LZMA_RESTRICT in, size_t *LZMA_RESTRICT in_pos,
+		size_t in_size, uint8_t *LZMA_RESTRICT out,
+		size_t *LZMA_RESTRICT out_pos, size_t out_size, lzma_action action)
+{
+	switch (coder->sequence) {
+	case SEQ_CODE: {
+		const size_t in_start = *in_pos;
+		const size_t out_start = *out_pos;
+
+		const lzma_ret ret = coder->next.code(coder->next.coder,
+				allocator, in, in_pos, in_size,
+				out, out_pos, out_size, action);
+
+		const size_t in_used = *in_pos - in_start;
+		const size_t out_used = *out_pos - out_start;
+
+		// NOTE: We compare to compressed_limit here, which prevents
+		// the total size of the Block growing past LZMA_VLI_MAX.
+		if (update_size(&coder->compressed_size, in_used,
+					coder->compressed_limit)
+				|| update_size(&coder->uncompressed_size,
+					out_used,
+					coder->block->uncompressed_size))
+			return LZMA_DATA_ERROR;
+
+		lzma_check_update(&coder->check, coder->block->check,
+				out + out_start, out_used);
+
+		if (ret != LZMA_STREAM_END)
+			return ret;
+
+		// Compressed and Uncompressed Sizes are now at their final
+		// values. Verify that they match the values given to us.
+		if (!is_size_valid(coder->compressed_size,
+					coder->block->compressed_size)
+				|| !is_size_valid(coder->uncompressed_size,
+					coder->block->uncompressed_size))
+			return LZMA_DATA_ERROR;
+
+		// Copy the values into coder->block. The caller
+		// may use this information to construct Index.
+		coder->block->compressed_size = coder->compressed_size;
+		coder->block->uncompressed_size = coder->uncompressed_size;
+
+		coder->sequence = SEQ_PADDING;
+	}
+
+	// Fall through
+
+	case SEQ_PADDING:
+		// Compressed Data is padded to a multiple of four bytes.
+		while (coder->compressed_size & 3) {
+			if (*in_pos >= in_size)
+				return LZMA_OK;
+
+			// We use compressed_size here just get the Padding
+			// right. The actual Compressed Size was stored to
+			// coder->block already, and won't be modified by
+			// us anymore.
+			++coder->compressed_size;
+
+			if (in[(*in_pos)++] != 0x00)
+				return LZMA_DATA_ERROR;
+		}
+
+		if (coder->block->check == LZMA_CHECK_NONE)
+			return LZMA_STREAM_END;
+
+		lzma_check_finish(&coder->check, coder->block->check);
+		coder->sequence = SEQ_CHECK;
+
+	// Fall through
+
+	case SEQ_CHECK: {
+		const size_t check_size = lzma_check_size(coder->block->check);
+		lzma_bufcpy(in, in_pos, in_size, coder->block->raw_check,
+				&coder->check_pos, check_size);
+		if (coder->check_pos < check_size)
+			return LZMA_OK;
+
+		// Validate the Check only if we support it.
+		// coder->check.buffer may be uninitialized
+		// when the Check ID is not supported.
+		if (lzma_check_is_supported(coder->block->check)
+				&& memcmp(coder->block->raw_check,
+					coder->check.buffer.u8,
+					check_size) != 0)
+			return LZMA_DATA_ERROR;
+
+		return LZMA_STREAM_END;
+	}
+	}
+
+	return LZMA_PROG_ERROR;
+}
+
+
+static void
+block_decoder_end(lzma_coder *coder, lzma_allocator *allocator)
+{
+	lzma_next_end(&coder->next, allocator);
+	lzma_free(coder, allocator);
+	return;
+}
+
+
+extern lzma_ret
+lzma_block_decoder_init(lzma_next_coder *next, lzma_allocator *allocator,
+		lzma_block *block)
+{
+	lzma_next_coder_init(&lzma_block_decoder_init, next, allocator);
+
+	// Validate the options. lzma_block_unpadded_size() does that for us
+	// except for Uncompressed Size and filters. Filters are validated
+	// by the raw decoder.
+	if (lzma_block_unpadded_size(block) == 0
+			|| !lzma_vli_is_valid(block->uncompressed_size))
+		return LZMA_PROG_ERROR;
+
+	// Allocate and initialize *next->coder if needed.
+	if (next->coder == NULL) {
+		next->coder = lzma_alloc(sizeof(lzma_coder), allocator);
+		if (next->coder == NULL)
+			return LZMA_MEM_ERROR;
+
+		next->code = &block_decode;
+		next->end = &block_decoder_end;
+		next->coder->next = LZMA_NEXT_CODER_INIT;
+	}
+
+	// Basic initializations
+	next->coder->sequence = SEQ_CODE;
+	next->coder->block = block;
+	next->coder->compressed_size = 0;
+	next->coder->uncompressed_size = 0;
+
+	// If Compressed Size is not known, we calculate the maximum allowed
+	// value so that encoded size of the Block (including Block Padding)
+	// is still a valid VLI and a multiple of four.
+	next->coder->compressed_limit
+			= block->compressed_size == LZMA_VLI_UNKNOWN
+				? (LZMA_VLI_MAX & ~LZMA_VLI_C(3))
+					- block->header_size
+					- lzma_check_size(block->check)
+				: block->compressed_size;
+
+	// Initialize the check. It's caller's problem if the Check ID is not
+	// supported, and the Block decoder cannot verify the Check field.
+	// Caller can test lzma_check_is_supported(block->check).
+	next->coder->check_pos = 0;
+	lzma_check_init(&next->coder->check, block->check);
+
+	// Initialize the filter chain.
+	return lzma_raw_decoder_init(&next->coder->next, allocator,
+			block->filters);
+}
+
+
+extern LZMA_API(lzma_ret)
+lzma_block_decoder(lzma_stream *strm, lzma_block *block)
+{
+	lzma_next_strm_init1(lzma_block_decoder_init, strm, block);
+
+	strm->internal->supported_actions[LZMA_RUN] = true;
+	strm->internal->supported_actions[LZMA_FINISH] = true;
+
+	return LZMA_OK;
+}
diff --git a/Utilities/cmliblzma/liblzma/common/block_decoder.h b/Utilities/cmliblzma/liblzma/common/block_decoder.h
new file mode 100644
index 0000000..7da9df6
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/block_decoder.h
@@ -0,0 +1,22 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       block_decoder.h
+/// \brief      Decodes .xz Blocks
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#ifndef LZMA_BLOCK_DECODER_H
+#define LZMA_BLOCK_DECODER_H
+
+#include "common.h"
+
+
+extern lzma_ret lzma_block_decoder_init(lzma_next_coder *next,
+		lzma_allocator *allocator, lzma_block *block);
+
+#endif
diff --git a/Utilities/cmliblzma/liblzma/common/block_encoder.c b/Utilities/cmliblzma/liblzma/common/block_encoder.c
new file mode 100644
index 0000000..ed74827
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/block_encoder.c
@@ -0,0 +1,217 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       block_encoder.c
+/// \brief      Encodes .xz Blocks
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "block_encoder.h"
+#include "filter_encoder.h"
+#include "check.h"
+
+
+struct lzma_coder_s {
+	/// The filters in the chain; initialized with lzma_raw_decoder_init().
+	lzma_next_coder next;
+
+	/// Encoding options; we also write Unpadded Size, Compressed Size,
+	/// and Uncompressed Size back to this structure when the encoding
+	/// has been finished.
+	lzma_block *block;
+
+	enum {
+		SEQ_CODE,
+		SEQ_PADDING,
+		SEQ_CHECK,
+	} sequence;
+
+	/// Compressed Size calculated while encoding
+	lzma_vli compressed_size;
+
+	/// Uncompressed Size calculated while encoding
+	lzma_vli uncompressed_size;
+
+	/// Position in the Check field
+	size_t pos;
+
+	/// Check of the uncompressed data
+	lzma_check_state check;
+};
+
+
+static lzma_ret
+block_encode(lzma_coder *coder, lzma_allocator *allocator,
+		const uint8_t *LZMA_RESTRICT in, size_t *LZMA_RESTRICT in_pos,
+		size_t in_size, uint8_t *LZMA_RESTRICT out,
+		size_t *LZMA_RESTRICT out_pos, size_t out_size, lzma_action action)
+{
+	// Check that our amount of input stays in proper limits.
+	if (LZMA_VLI_MAX - coder->uncompressed_size < in_size - *in_pos)
+		return LZMA_DATA_ERROR;
+
+	switch (coder->sequence) {
+	case SEQ_CODE: {
+		const size_t in_start = *in_pos;
+		const size_t out_start = *out_pos;
+
+		const lzma_ret ret = coder->next.code(coder->next.coder,
+				allocator, in, in_pos, in_size,
+				out, out_pos, out_size, action);
+
+		const size_t in_used = *in_pos - in_start;
+		const size_t out_used = *out_pos - out_start;
+
+		if (COMPRESSED_SIZE_MAX - coder->compressed_size < out_used)
+			return LZMA_DATA_ERROR;
+
+		coder->compressed_size += out_used;
+
+		// No need to check for overflow because we have already
+		// checked it at the beginning of this function.
+		coder->uncompressed_size += in_used;
+
+		lzma_check_update(&coder->check, coder->block->check,
+				in + in_start, in_used);
+
+		if (ret != LZMA_STREAM_END || action == LZMA_SYNC_FLUSH)
+			return ret;
+
+		assert(*in_pos == in_size);
+		assert(action == LZMA_FINISH);
+
+		// Copy the values into coder->block. The caller
+		// may use this information to construct Index.
+		coder->block->compressed_size = coder->compressed_size;
+		coder->block->uncompressed_size = coder->uncompressed_size;
+
+		coder->sequence = SEQ_PADDING;
+	}
+
+	// Fall through
+
+	case SEQ_PADDING:
+		// Pad Compressed Data to a multiple of four bytes. We can
+		// use coder->compressed_size for this since we don't need
+		// it for anything else anymore.
+		while (coder->compressed_size & 3) {
+			if (*out_pos >= out_size)
+				return LZMA_OK;
+
+			out[*out_pos] = 0x00;
+			++*out_pos;
+			++coder->compressed_size;
+		}
+
+		if (coder->block->check == LZMA_CHECK_NONE)
+			return LZMA_STREAM_END;
+
+		lzma_check_finish(&coder->check, coder->block->check);
+
+		coder->sequence = SEQ_CHECK;
+
+	// Fall through
+
+	case SEQ_CHECK: {
+		const size_t check_size = lzma_check_size(coder->block->check);
+		lzma_bufcpy(coder->check.buffer.u8, &coder->pos, check_size,
+				out, out_pos, out_size);
+		if (coder->pos < check_size)
+			return LZMA_OK;
+
+		memcpy(coder->block->raw_check, coder->check.buffer.u8,
+				check_size);
+		return LZMA_STREAM_END;
+	}
+	}
+
+	return LZMA_PROG_ERROR;
+}
+
+
+static void
+block_encoder_end(lzma_coder *coder, lzma_allocator *allocator)
+{
+	lzma_next_end(&coder->next, allocator);
+	lzma_free(coder, allocator);
+	return;
+}
+
+
+static lzma_ret
+block_encoder_update(lzma_coder *coder, lzma_allocator *allocator,
+		const lzma_filter *filters lzma_attribute((__unused__)),
+		const lzma_filter *reversed_filters)
+{
+	if (coder->sequence != SEQ_CODE)
+		return LZMA_PROG_ERROR;
+
+	return lzma_next_filter_update(
+			&coder->next, allocator, reversed_filters);
+}
+
+
+extern lzma_ret
+lzma_block_encoder_init(lzma_next_coder *next, lzma_allocator *allocator,
+		lzma_block *block)
+{
+	lzma_next_coder_init(&lzma_block_encoder_init, next, allocator);
+
+	if (block == NULL)
+		return LZMA_PROG_ERROR;
+
+	// The contents of the structure may depend on the version so
+	// check the version first.
+	if (block->version != 0)
+		return LZMA_OPTIONS_ERROR;
+
+	// If the Check ID is not supported, we cannot calculate the check and
+	// thus not create a proper Block.
+	if ((unsigned int)(block->check) > LZMA_CHECK_ID_MAX)
+		return LZMA_PROG_ERROR;
+
+	if (!lzma_check_is_supported(block->check))
+		return LZMA_UNSUPPORTED_CHECK;
+
+	// Allocate and initialize *next->coder if needed.
+	if (next->coder == NULL) {
+		next->coder = lzma_alloc(sizeof(lzma_coder), allocator);
+		if (next->coder == NULL)
+			return LZMA_MEM_ERROR;
+
+		next->code = &block_encode;
+		next->end = &block_encoder_end;
+		next->update = &block_encoder_update;
+		next->coder->next = LZMA_NEXT_CODER_INIT;
+	}
+
+	// Basic initializations
+	next->coder->sequence = SEQ_CODE;
+	next->coder->block = block;
+	next->coder->compressed_size = 0;
+	next->coder->uncompressed_size = 0;
+	next->coder->pos = 0;
+
+	// Initialize the check
+	lzma_check_init(&next->coder->check, block->check);
+
+	// Initialize the requested filters.
+	return lzma_raw_encoder_init(&next->coder->next, allocator,
+			block->filters);
+}
+
+
+extern LZMA_API(lzma_ret)
+lzma_block_encoder(lzma_stream *strm, lzma_block *block)
+{
+	lzma_next_strm_init1(lzma_block_encoder_init, strm, block);
+
+	strm->internal->supported_actions[LZMA_RUN] = true;
+	strm->internal->supported_actions[LZMA_FINISH] = true;
+
+	return LZMA_OK;
+}
diff --git a/Utilities/cmliblzma/liblzma/common/block_encoder.h b/Utilities/cmliblzma/liblzma/common/block_encoder.h
new file mode 100644
index 0000000..b9eff0b
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/block_encoder.h
@@ -0,0 +1,47 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       block_encoder.h
+/// \brief      Encodes .xz Blocks
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#ifndef LZMA_BLOCK_ENCODER_H
+#define LZMA_BLOCK_ENCODER_H
+
+#include "common.h"
+
+
+/// \brief      Biggest Compressed Size value that the Block encoder supports
+///
+/// The maximum size of a single Block is limited by the maximum size of
+/// a Stream, which in theory is 2^63 - 3 bytes (i.e. LZMA_VLI_MAX - 3).
+/// While the size is really big and no one should hit it in practice, we
+/// take it into account in some places anyway to catch some errors e.g. if
+/// application passes insanely big value to some function.
+///
+/// We could take into account the headers etc. to determine the exact
+/// maximum size of the Compressed Data field, but the complexity would give
+/// us nothing useful. Instead, limit the size of Compressed Data so that
+/// even with biggest possible Block Header and Check fields the total
+/// encoded size of the Block stays as a valid VLI. This doesn't guarantee
+/// that the size of the Stream doesn't grow too big, but that problem is
+/// taken care outside the Block handling code.
+///
+/// ~LZMA_VLI_C(3) is to guarantee that if we need padding at the end of
+/// the Compressed Data field, it will still stay in the proper limit.
+///
+/// This constant is in this file because it is needed in both
+/// block_encoder.c and block_buffer_encoder.c.
+#define COMPRESSED_SIZE_MAX ((LZMA_VLI_MAX - LZMA_BLOCK_HEADER_SIZE_MAX \
+		- LZMA_CHECK_SIZE_MAX) & ~LZMA_VLI_C(3))
+
+
+extern lzma_ret lzma_block_encoder_init(lzma_next_coder *next,
+		lzma_allocator *allocator, lzma_block *block);
+
+#endif
diff --git a/Utilities/cmliblzma/liblzma/common/block_header_decoder.c b/Utilities/cmliblzma/liblzma/common/block_header_decoder.c
new file mode 100644
index 0000000..f6e470e
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/block_header_decoder.c
@@ -0,0 +1,121 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       block_header_decoder.c
+/// \brief      Decodes Block Header from .xz files
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "common.h"
+#include "check.h"
+
+
+static void
+free_properties(lzma_block *block, lzma_allocator *allocator)
+{
+	size_t i;
+
+	// Free allocated filter options. The last array member is not
+	// touched after the initialization in the beginning of
+	// lzma_block_header_decode(), so we don't need to touch that here.
+	for (i = 0; i < LZMA_FILTERS_MAX; ++i) {
+		lzma_free(block->filters[i].options, allocator);
+		block->filters[i].id = LZMA_VLI_UNKNOWN;
+		block->filters[i].options = NULL;
+	}
+
+	return;
+}
+
+
+extern LZMA_API(lzma_ret)
+lzma_block_header_decode(lzma_block *block,
+		lzma_allocator *allocator, const uint8_t *in)
+{
+	const size_t filter_count = (in[1] & 3) + 1;
+	size_t in_size;
+	size_t i;
+
+	// Start after the Block Header Size and Block Flags fields.
+	size_t in_pos = 2;
+
+	// NOTE: We consider the header to be corrupt not only when the
+	// CRC32 doesn't match, but also when variable-length integers
+	// are invalid or over 63 bits, or if the header is too small
+	// to contain the claimed information.
+
+	// Initialize the filter options array. This way the caller can
+	// safely free() the options even if an error occurs in this function.
+	for (i = 0; i <= LZMA_FILTERS_MAX; ++i) {
+		block->filters[i].id = LZMA_VLI_UNKNOWN;
+		block->filters[i].options = NULL;
+	}
+
+	// Always zero for now.
+	block->version = 0;
+
+	// Validate Block Header Size and Check type. The caller must have
+	// already set these, so it is a programming error if this test fails.
+	if (lzma_block_header_size_decode(in[0]) != block->header_size
+			|| (unsigned int)(block->check) > LZMA_CHECK_ID_MAX)
+		return LZMA_PROG_ERROR;
+
+	// Exclude the CRC32 field.
+	in_size = block->header_size - 4;
+
+	// Verify CRC32
+	if (lzma_crc32(in, in_size, 0) != unaligned_read32le(in + in_size))
+		return LZMA_DATA_ERROR;
+
+	// Check for unsupported flags.
+	if (in[1] & 0x3C)
+		return LZMA_OPTIONS_ERROR;
+
+	// Compressed Size
+	if (in[1] & 0x40) {
+		return_if_error(lzma_vli_decode(&block->compressed_size,
+				NULL, in, &in_pos, in_size));
+
+		// Validate Compressed Size. This checks that it isn't zero
+		// and that the total size of the Block is a valid VLI.
+		if (lzma_block_unpadded_size(block) == 0)
+			return LZMA_DATA_ERROR;
+	} else {
+		block->compressed_size = LZMA_VLI_UNKNOWN;
+	}
+
+	// Uncompressed Size
+	if (in[1] & 0x80)
+		return_if_error(lzma_vli_decode(&block->uncompressed_size,
+				NULL, in, &in_pos, in_size));
+	else
+		block->uncompressed_size = LZMA_VLI_UNKNOWN;
+
+	// Filter Flags
+	for (i = 0; i < filter_count; ++i) {
+		const lzma_ret ret = lzma_filter_flags_decode(
+				&block->filters[i], allocator,
+				in, &in_pos, in_size);
+		if (ret != LZMA_OK) {
+			free_properties(block, allocator);
+			return ret;
+		}
+	}
+
+	// Padding
+	while (in_pos < in_size) {
+		if (in[in_pos++] != 0x00) {
+			free_properties(block, allocator);
+
+			// Possibly some new field present so use
+			// LZMA_OPTIONS_ERROR instead of LZMA_DATA_ERROR.
+			return LZMA_OPTIONS_ERROR;
+		}
+	}
+
+	return LZMA_OK;
+}
diff --git a/Utilities/cmliblzma/liblzma/common/block_header_encoder.c b/Utilities/cmliblzma/liblzma/common/block_header_encoder.c
new file mode 100644
index 0000000..650295c
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/block_header_encoder.c
@@ -0,0 +1,137 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       block_header_encoder.c
+/// \brief      Encodes Block Header for .xz files
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "common.h"
+#include "check.h"
+
+
+extern LZMA_API(lzma_ret)
+lzma_block_header_size(lzma_block *block)
+{
+	size_t i;
+
+	// Block Header Size + Block Flags + CRC32.
+	uint32_t size = 1 + 1 + 4;
+
+	if (block->version != 0)
+		return LZMA_OPTIONS_ERROR;
+
+	// Compressed Size
+	if (block->compressed_size != LZMA_VLI_UNKNOWN) {
+		const uint32_t add = lzma_vli_size(block->compressed_size);
+		if (add == 0 || block->compressed_size == 0)
+			return LZMA_PROG_ERROR;
+
+		size += add;
+	}
+
+	// Uncompressed Size
+	if (block->uncompressed_size != LZMA_VLI_UNKNOWN) {
+		const uint32_t add = lzma_vli_size(block->uncompressed_size);
+		if (add == 0)
+			return LZMA_PROG_ERROR;
+
+		size += add;
+	}
+
+	// List of Filter Flags
+	if (block->filters == NULL || block->filters[0].id == LZMA_VLI_UNKNOWN)
+		return LZMA_PROG_ERROR;
+
+	for (i = 0; block->filters[i].id != LZMA_VLI_UNKNOWN; ++i) {
+		uint32_t add;
+
+		// Don't allow too many filters.
+		if (i == LZMA_FILTERS_MAX)
+			return LZMA_PROG_ERROR;
+
+		return_if_error(lzma_filter_flags_size(&add,
+				block->filters + i));
+
+		size += add;
+	}
+
+	// Pad to a multiple of four bytes.
+	block->header_size = (size + 3) & ~UINT32_C(3);
+
+	// NOTE: We don't verify that the encoded size of the Block stays
+	// within limits. This is because it is possible that we are called
+	// with exaggerated Compressed Size (e.g. LZMA_VLI_MAX) to reserve
+	// space for Block Header, and later called again with lower,
+	// real values.
+
+	return LZMA_OK;
+}
+
+
+extern LZMA_API(lzma_ret)
+lzma_block_header_encode(const lzma_block *block, uint8_t *out)
+{
+	size_t out_size;
+	size_t out_pos = 2;
+	size_t filter_count = 0;
+
+	// Validate everything but filters.
+	if (lzma_block_unpadded_size(block) == 0
+			|| !lzma_vli_is_valid(block->uncompressed_size))
+		return LZMA_PROG_ERROR;
+
+	// Indicate the size of the buffer _excluding_ the CRC32 field.
+	out_size = block->header_size - 4;
+
+	// Store the Block Header Size.
+	out[0] = out_size / 4;
+
+	// We write Block Flags in pieces.
+	out[1] = 0x00;
+
+	// Compressed Size
+	if (block->compressed_size != LZMA_VLI_UNKNOWN) {
+		return_if_error(lzma_vli_encode(block->compressed_size, NULL,
+				out, &out_pos, out_size));
+
+		out[1] |= 0x40;
+	}
+
+	// Uncompressed Size
+	if (block->uncompressed_size != LZMA_VLI_UNKNOWN) {
+		return_if_error(lzma_vli_encode(block->uncompressed_size, NULL,
+				out, &out_pos, out_size));
+
+		out[1] |= 0x80;
+	}
+
+	// Filter Flags
+	if (block->filters == NULL || block->filters[0].id == LZMA_VLI_UNKNOWN)
+		return LZMA_PROG_ERROR;
+
+	do {
+		// There can be a maximum of four filters.
+		if (filter_count == LZMA_FILTERS_MAX)
+			return LZMA_PROG_ERROR;
+
+		return_if_error(lzma_filter_flags_encode(
+				block->filters + filter_count,
+				out, &out_pos, out_size));
+
+	} while (block->filters[++filter_count].id != LZMA_VLI_UNKNOWN);
+
+	out[1] |= filter_count - 1;
+
+	// Padding
+	memzero(out + out_pos, out_size - out_pos);
+
+	// CRC32
+	unaligned_write32le(out + out_size, lzma_crc32(out, out_size, 0));
+
+	return LZMA_OK;
+}
diff --git a/Utilities/cmliblzma/liblzma/common/block_util.c b/Utilities/cmliblzma/liblzma/common/block_util.c
new file mode 100644
index 0000000..4cd34d1
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/block_util.c
@@ -0,0 +1,95 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       block_header.c
+/// \brief      Utility functions to handle lzma_block
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "common.h"
+#include "index.h"
+
+
+extern LZMA_API(lzma_ret)
+lzma_block_compressed_size(lzma_block *block, lzma_vli unpadded_size)
+{
+	uint32_t container_size;
+	lzma_vli compressed_size;
+
+	// Validate everything but Uncompressed Size and filters.
+	if (lzma_block_unpadded_size(block) == 0)
+		return LZMA_PROG_ERROR;
+
+	container_size = block->header_size
+			+ lzma_check_size(block->check);
+
+	// Validate that Compressed Size will be greater than zero.
+	if (unpadded_size <= container_size)
+		return LZMA_DATA_ERROR;
+
+	// Calculate what Compressed Size is supposed to be.
+	// If Compressed Size was present in Block Header,
+	// compare that the new value matches it.
+	compressed_size = unpadded_size - container_size;
+	if (block->compressed_size != LZMA_VLI_UNKNOWN
+			&& block->compressed_size != compressed_size)
+		return LZMA_DATA_ERROR;
+
+	block->compressed_size = compressed_size;
+
+	return LZMA_OK;
+}
+
+
+extern LZMA_API(lzma_vli)
+lzma_block_unpadded_size(const lzma_block *block)
+{
+	lzma_vli unpadded_size;
+
+	// Validate the values that we are interested in i.e. all but
+	// Uncompressed Size and the filters.
+	//
+	// NOTE: This function is used for validation too, so it is
+	// essential that these checks are always done even if
+	// Compressed Size is unknown.
+	if (block == NULL || block->version != 0
+			|| block->header_size < LZMA_BLOCK_HEADER_SIZE_MIN
+			|| block->header_size > LZMA_BLOCK_HEADER_SIZE_MAX
+			|| (block->header_size & 3)
+			|| !lzma_vli_is_valid(block->compressed_size)
+			|| block->compressed_size == 0
+			|| (unsigned int)(block->check) > LZMA_CHECK_ID_MAX)
+		return 0;
+
+	// If Compressed Size is unknown, return that we cannot know
+	// size of the Block either.
+	if (block->compressed_size == LZMA_VLI_UNKNOWN)
+		return LZMA_VLI_UNKNOWN;
+
+	// Calculate Unpadded Size and validate it.
+	unpadded_size = block->compressed_size
+				+ block->header_size
+				+ lzma_check_size(block->check);
+
+	assert(unpadded_size >= UNPADDED_SIZE_MIN);
+	if (unpadded_size > UNPADDED_SIZE_MAX)
+		return 0;
+
+	return unpadded_size;
+}
+
+
+extern LZMA_API(lzma_vli)
+lzma_block_total_size(const lzma_block *block)
+{
+	lzma_vli unpadded_size = lzma_block_unpadded_size(block);
+
+	if (unpadded_size != LZMA_VLI_UNKNOWN)
+		unpadded_size = vli_ceil4(unpadded_size);
+
+	return unpadded_size;
+}
diff --git a/Utilities/cmliblzma/liblzma/common/common.c b/Utilities/cmliblzma/liblzma/common/common.c
new file mode 100644
index 0000000..2e723c8
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/common.c
@@ -0,0 +1,390 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       common.h
+/// \brief      Common functions needed in many places in liblzma
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "common.h"
+
+
+/////////////
+// Version //
+/////////////
+
+extern LZMA_API(uint32_t)
+lzma_version_number(void)
+{
+	return LZMA_VERSION;
+}
+
+
+extern LZMA_API(const char *)
+lzma_version_string(void)
+{
+	return LZMA_VERSION_STRING;
+}
+
+
+///////////////////////
+// Memory allocation //
+///////////////////////
+
+extern void * lzma_attribute((__malloc__)) lzma_attr_alloc_size(1)
+lzma_alloc(size_t size, lzma_allocator *allocator)
+{
+	void *ptr;
+
+	// Some malloc() variants return NULL if called with size == 0.
+	if (size == 0)
+		size = 1;
+
+	if (allocator != NULL && allocator->alloc != NULL)
+		ptr = allocator->alloc(allocator->opaque, 1, size);
+	else
+		ptr = malloc(size);
+
+	return ptr;
+}
+
+
+extern void
+lzma_free(void *ptr, lzma_allocator *allocator)
+{
+	if (allocator != NULL && allocator->free != NULL)
+		allocator->free(allocator->opaque, ptr);
+	else
+		free(ptr);
+
+	return;
+}
+
+
+//////////
+// Misc //
+//////////
+
+extern size_t
+lzma_bufcpy(const uint8_t *LZMA_RESTRICT in, size_t *LZMA_RESTRICT in_pos,
+		size_t in_size, uint8_t *LZMA_RESTRICT out,
+		size_t *LZMA_RESTRICT out_pos, size_t out_size)
+{
+	const size_t in_avail = in_size - *in_pos;
+	const size_t out_avail = out_size - *out_pos;
+	const size_t copy_size = my_min(in_avail, out_avail);
+
+	memcpy(out + *out_pos, in + *in_pos, copy_size);
+
+	*in_pos += copy_size;
+	*out_pos += copy_size;
+
+	return copy_size;
+}
+
+
+extern lzma_ret
+lzma_next_filter_init(lzma_next_coder *next, lzma_allocator *allocator,
+		const lzma_filter_info *filters)
+{
+	lzma_next_coder_init(filters[0].init, next, allocator);
+	next->id = filters[0].id;
+	return filters[0].init == NULL
+			? LZMA_OK : filters[0].init(next, allocator, filters);
+}
+
+
+extern lzma_ret
+lzma_next_filter_update(lzma_next_coder *next, lzma_allocator *allocator,
+		const lzma_filter *reversed_filters)
+{
+	// Check that the application isn't trying to change the Filter ID.
+	// End of filters is indicated with LZMA_VLI_UNKNOWN in both
+	// reversed_filters[0].id and next->id.
+	if (reversed_filters[0].id != next->id)
+		return LZMA_PROG_ERROR;
+
+	if (reversed_filters[0].id == LZMA_VLI_UNKNOWN)
+		return LZMA_OK;
+
+	assert(next->update != NULL);
+	return next->update(next->coder, allocator, NULL, reversed_filters);
+}
+
+
+extern void
+lzma_next_end(lzma_next_coder *next, lzma_allocator *allocator)
+{
+	if (next->init != (uintptr_t)(NULL)) {
+		// To avoid tiny end functions that simply call
+		// lzma_free(coder, allocator), we allow leaving next->end
+		// NULL and call lzma_free() here.
+		if (next->end != NULL)
+			next->end(next->coder, allocator);
+		else
+			lzma_free(next->coder, allocator);
+
+		// Reset the variables so the we don't accidentally think
+		// that it is an already initialized coder.
+		*next = LZMA_NEXT_CODER_INIT;
+	}
+
+	return;
+}
+
+
+//////////////////////////////////////
+// External to internal API wrapper //
+//////////////////////////////////////
+
+extern lzma_ret
+lzma_strm_init(lzma_stream *strm)
+{
+	if (strm == NULL)
+		return LZMA_PROG_ERROR;
+
+	if (strm->internal == NULL) {
+		strm->internal = lzma_alloc(sizeof(lzma_internal),
+				strm->allocator);
+		if (strm->internal == NULL)
+			return LZMA_MEM_ERROR;
+
+		strm->internal->next = LZMA_NEXT_CODER_INIT;
+	}
+
+	strm->internal->supported_actions[LZMA_RUN] = false;
+	strm->internal->supported_actions[LZMA_SYNC_FLUSH] = false;
+	strm->internal->supported_actions[LZMA_FULL_FLUSH] = false;
+	strm->internal->supported_actions[LZMA_FINISH] = false;
+	strm->internal->sequence = ISEQ_RUN;
+	strm->internal->allow_buf_error = false;
+
+	strm->total_in = 0;
+	strm->total_out = 0;
+
+	return LZMA_OK;
+}
+
+
+extern LZMA_API(lzma_ret)
+lzma_code(lzma_stream *strm, lzma_action action)
+{
+	size_t in_pos = 0;
+	size_t out_pos = 0;
+	lzma_ret ret;
+
+	// Sanity checks
+	if ((strm->next_in == NULL && strm->avail_in != 0)
+			|| (strm->next_out == NULL && strm->avail_out != 0)
+			|| strm->internal == NULL
+			|| strm->internal->next.code == NULL
+			|| (unsigned int)(action) > LZMA_FINISH
+			|| !strm->internal->supported_actions[action])
+		return LZMA_PROG_ERROR;
+
+	// Check if unsupported members have been set to non-zero or non-NULL,
+	// which would indicate that some new feature is wanted.
+	if (strm->reserved_ptr1 != NULL
+			|| strm->reserved_ptr2 != NULL
+			|| strm->reserved_ptr3 != NULL
+			|| strm->reserved_ptr4 != NULL
+			|| strm->reserved_int1 != 0
+			|| strm->reserved_int2 != 0
+			|| strm->reserved_int3 != 0
+			|| strm->reserved_int4 != 0
+			|| strm->reserved_enum1 != LZMA_RESERVED_ENUM
+			|| strm->reserved_enum2 != LZMA_RESERVED_ENUM)
+		return LZMA_OPTIONS_ERROR;
+
+	switch (strm->internal->sequence) {
+	case ISEQ_RUN:
+		switch (action) {
+		case LZMA_RUN:
+			break;
+
+		case LZMA_SYNC_FLUSH:
+			strm->internal->sequence = ISEQ_SYNC_FLUSH;
+			break;
+
+		case LZMA_FULL_FLUSH:
+			strm->internal->sequence = ISEQ_FULL_FLUSH;
+			break;
+
+		case LZMA_FINISH:
+			strm->internal->sequence = ISEQ_FINISH;
+			break;
+		}
+
+		break;
+
+	case ISEQ_SYNC_FLUSH:
+		// The same action must be used until we return
+		// LZMA_STREAM_END, and the amount of input must not change.
+		if (action != LZMA_SYNC_FLUSH
+				|| strm->internal->avail_in != strm->avail_in)
+			return LZMA_PROG_ERROR;
+
+		break;
+
+	case ISEQ_FULL_FLUSH:
+		if (action != LZMA_FULL_FLUSH
+				|| strm->internal->avail_in != strm->avail_in)
+			return LZMA_PROG_ERROR;
+
+		break;
+
+	case ISEQ_FINISH:
+		if (action != LZMA_FINISH
+				|| strm->internal->avail_in != strm->avail_in)
+			return LZMA_PROG_ERROR;
+
+		break;
+
+	case ISEQ_END:
+		return LZMA_STREAM_END;
+
+	case ISEQ_ERROR:
+	default:
+		return LZMA_PROG_ERROR;
+	}
+
+	ret = strm->internal->next.code(
+			strm->internal->next.coder, strm->allocator,
+			strm->next_in, &in_pos, strm->avail_in,
+			strm->next_out, &out_pos, strm->avail_out, action);
+
+	strm->next_in += in_pos;
+	strm->avail_in -= in_pos;
+	strm->total_in += in_pos;
+
+	strm->next_out += out_pos;
+	strm->avail_out -= out_pos;
+	strm->total_out += out_pos;
+
+	strm->internal->avail_in = strm->avail_in;
+
+	switch (ret) {
+	case LZMA_OK:
+		// Don't return LZMA_BUF_ERROR when it happens the first time.
+		// This is to avoid returning LZMA_BUF_ERROR when avail_out
+		// was zero but still there was no more data left to written
+		// to next_out.
+		if (out_pos == 0 && in_pos == 0) {
+			if (strm->internal->allow_buf_error)
+				ret = LZMA_BUF_ERROR;
+			else
+				strm->internal->allow_buf_error = true;
+		} else {
+			strm->internal->allow_buf_error = false;
+		}
+		break;
+
+	case LZMA_STREAM_END:
+		if (strm->internal->sequence == ISEQ_SYNC_FLUSH
+				|| strm->internal->sequence == ISEQ_FULL_FLUSH)
+			strm->internal->sequence = ISEQ_RUN;
+		else
+			strm->internal->sequence = ISEQ_END;
+
+	// Fall through
+
+	case LZMA_NO_CHECK:
+	case LZMA_UNSUPPORTED_CHECK:
+	case LZMA_GET_CHECK:
+	case LZMA_MEMLIMIT_ERROR:
+		// Something else than LZMA_OK, but not a fatal error,
+		// that is, coding may be continued (except if ISEQ_END).
+		strm->internal->allow_buf_error = false;
+		break;
+
+	default:
+		// All the other errors are fatal; coding cannot be continued.
+		assert(ret != LZMA_BUF_ERROR);
+		strm->internal->sequence = ISEQ_ERROR;
+		break;
+	}
+
+	return ret;
+}
+
+
+extern LZMA_API(void)
+lzma_end(lzma_stream *strm)
+{
+	if (strm != NULL && strm->internal != NULL) {
+		lzma_next_end(&strm->internal->next, strm->allocator);
+		lzma_free(strm->internal, strm->allocator);
+		strm->internal = NULL;
+	}
+
+	return;
+}
+
+
+extern LZMA_API(lzma_check)
+lzma_get_check(const lzma_stream *strm)
+{
+	// Return LZMA_CHECK_NONE if we cannot know the check type.
+	// It's a bug in the application if this happens.
+	if (strm->internal->next.get_check == NULL)
+		return LZMA_CHECK_NONE;
+
+	return strm->internal->next.get_check(strm->internal->next.coder);
+}
+
+
+extern LZMA_API(uint64_t)
+lzma_memusage(const lzma_stream *strm)
+{
+	uint64_t memusage;
+	uint64_t old_memlimit;
+
+	if (strm == NULL || strm->internal == NULL
+			|| strm->internal->next.memconfig == NULL
+			|| strm->internal->next.memconfig(
+				strm->internal->next.coder,
+				&memusage, &old_memlimit, 0) != LZMA_OK)
+		return 0;
+
+	return memusage;
+}
+
+
+extern LZMA_API(uint64_t)
+lzma_memlimit_get(const lzma_stream *strm)
+{
+	uint64_t old_memlimit;
+	uint64_t memusage;
+
+	if (strm == NULL || strm->internal == NULL
+			|| strm->internal->next.memconfig == NULL
+			|| strm->internal->next.memconfig(
+				strm->internal->next.coder,
+				&memusage, &old_memlimit, 0) != LZMA_OK)
+		return 0;
+
+	return old_memlimit;
+}
+
+
+extern LZMA_API(lzma_ret)
+lzma_memlimit_set(lzma_stream *strm, uint64_t new_memlimit)
+{
+	// Dummy variables to simplify memconfig functions
+	uint64_t old_memlimit;
+	uint64_t memusage;
+
+	if (strm == NULL || strm->internal == NULL
+			|| strm->internal->next.memconfig == NULL)
+		return LZMA_PROG_ERROR;
+
+	if (new_memlimit != 0 && new_memlimit < LZMA_MEMUSAGE_BASE)
+		return LZMA_MEMLIMIT_ERROR;
+
+	return strm->internal->next.memconfig(strm->internal->next.coder,
+			&memusage, &old_memlimit, new_memlimit);
+}
diff --git a/Utilities/cmliblzma/liblzma/common/common.h b/Utilities/cmliblzma/liblzma/common/common.h
new file mode 100644
index 0000000..a6a2818
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/common.h
@@ -0,0 +1,305 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       common.h
+/// \brief      Definitions common to the whole liblzma library
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#ifndef LZMA_COMMON_H
+#define LZMA_COMMON_H
+
+#include "sysdefs.h"
+#include "tuklib_integer.h"
+
+#if defined(_WIN32) || defined(__CYGWIN__)
+#	ifdef DLL_EXPORT
+#		define LZMA_API_EXPORT __declspec(dllexport)
+#	else
+#		define LZMA_API_EXPORT
+#	endif
+// Don't use ifdef or defined() below.
+#elif HAVE_VISIBILITY
+#	define LZMA_API_EXPORT __attribute__((__visibility__("default")))
+#else
+#	define LZMA_API_EXPORT
+#endif
+
+#define LZMA_API(type) LZMA_API_EXPORT type LZMA_API_CALL
+
+#include "lzma.h"
+
+// These allow helping the compiler in some often-executed branches, whose
+// result is almost always the same.
+#ifdef __GNUC__
+#	define likely(expr) __builtin_expect(expr, true)
+#	define unlikely(expr) __builtin_expect(expr, false)
+#else
+#	define likely(expr) (expr)
+#	define unlikely(expr) (expr)
+#endif
+
+
+/// Size of temporary buffers needed in some filters
+#define LZMA_BUFFER_SIZE 4096
+
+
+/// Starting value for memory usage estimates. Instead of calculating size
+/// of _every_ structure and taking into account malloc() overhead etc., we
+/// add a base size to all memory usage estimates. It's not very accurate
+/// but should be easily good enough.
+#define LZMA_MEMUSAGE_BASE (UINT64_C(1) << 15)
+
+/// Start of internal Filter ID space. These IDs must never be used
+/// in Streams.
+#define LZMA_FILTER_RESERVED_START (LZMA_VLI_C(1) << 62)
+
+
+/// Supported flags that can be passed to lzma_stream_decoder()
+/// or lzma_auto_decoder().
+#define LZMA_SUPPORTED_FLAGS \
+	( LZMA_TELL_NO_CHECK \
+	| LZMA_TELL_UNSUPPORTED_CHECK \
+	| LZMA_TELL_ANY_CHECK \
+	| LZMA_CONCATENATED )
+
+
+/// Type of encoder/decoder specific data; the actual structure is defined
+/// differently in different coders.
+typedef struct lzma_coder_s lzma_coder;
+
+typedef struct lzma_next_coder_s lzma_next_coder;
+
+typedef struct lzma_filter_info_s lzma_filter_info;
+
+
+/// Type of a function used to initialize a filter encoder or decoder
+typedef lzma_ret (*lzma_init_function)(
+		lzma_next_coder *next, lzma_allocator *allocator,
+		const lzma_filter_info *filters);
+
+/// Type of a function to do some kind of coding work (filters, Stream,
+/// Block encoders/decoders etc.). Some special coders use don't use both
+/// input and output buffers, but for simplicity they still use this same
+/// function prototype.
+typedef lzma_ret (*lzma_code_function)(
+		lzma_coder *coder, lzma_allocator *allocator,
+		const uint8_t *LZMA_RESTRICT in, size_t *LZMA_RESTRICT in_pos,
+		size_t in_size, uint8_t *LZMA_RESTRICT out,
+		size_t *LZMA_RESTRICT out_pos, size_t out_size,
+		lzma_action action);
+
+/// Type of a function to free the memory allocated for the coder
+typedef void (*lzma_end_function)(
+		lzma_coder *coder, lzma_allocator *allocator);
+
+
+/// Raw coder validates and converts an array of lzma_filter structures to
+/// an array of lzma_filter_info structures. This array is used with
+/// lzma_next_filter_init to initialize the filter chain.
+struct lzma_filter_info_s {
+	/// Filter ID. This is used only by the encoder
+	/// with lzma_filters_update().
+	lzma_vli id;
+
+	/// Pointer to function used to initialize the filter.
+	/// This is NULL to indicate end of array.
+	lzma_init_function init;
+
+	/// Pointer to filter's options structure
+	void *options;
+};
+
+
+/// Hold data and function pointers of the next filter in the chain.
+struct lzma_next_coder_s {
+	/// Pointer to coder-specific data
+	lzma_coder *coder;
+
+	/// Filter ID. This is LZMA_VLI_UNKNOWN when this structure doesn't
+	/// point to a filter coder.
+	lzma_vli id;
+
+	/// "Pointer" to init function. This is never called here.
+	/// We need only to detect if we are initializing a coder
+	/// that was allocated earlier. See lzma_next_coder_init and
+	/// lzma_next_strm_init macros in this file.
+	uintptr_t init;
+
+	/// Pointer to function to do the actual coding
+	lzma_code_function code;
+
+	/// Pointer to function to free lzma_next_coder.coder. This can
+	/// be NULL; in that case, lzma_free is called to free
+	/// lzma_next_coder.coder.
+	lzma_end_function end;
+
+	/// Pointer to function to return the type of the integrity check.
+	/// Most coders won't support this.
+	lzma_check (*get_check)(const lzma_coder *coder);
+
+	/// Pointer to function to get and/or change the memory usage limit.
+	/// If new_memlimit == 0, the limit is not changed.
+	lzma_ret (*memconfig)(lzma_coder *coder, uint64_t *memusage,
+			uint64_t *old_memlimit, uint64_t new_memlimit);
+
+	/// Update the filter-specific options or the whole filter chain
+	/// in the encoder.
+	lzma_ret (*update)(lzma_coder *coder, lzma_allocator *allocator,
+			const lzma_filter *filters,
+			const lzma_filter *reversed_filters);
+};
+
+
+/// Constant to initialize lzma_next_coder structure
+static const lzma_next_coder LZMA_NEXT_CODER_INIT =
+	{
+		NULL,
+		LZMA_VLI_UNKNOWN,
+		(uintptr_t)(NULL),
+		NULL,
+		NULL,
+		NULL,
+		NULL,
+		NULL,
+	};
+
+
+/// Internal data for lzma_strm_init, lzma_code, and lzma_end. A pointer to
+/// this is stored in lzma_stream.
+struct lzma_internal_s {
+	/// The actual coder that should do something useful
+	lzma_next_coder next;
+
+	/// Track the state of the coder. This is used to validate arguments
+	/// so that the actual coders can rely on e.g. that LZMA_SYNC_FLUSH
+	/// is used on every call to lzma_code until next.code has returned
+	/// LZMA_STREAM_END.
+	enum {
+		ISEQ_RUN,
+		ISEQ_SYNC_FLUSH,
+		ISEQ_FULL_FLUSH,
+		ISEQ_FINISH,
+		ISEQ_END,
+		ISEQ_ERROR,
+	} sequence;
+
+	/// A copy of lzma_stream avail_in. This is used to verify that the
+	/// amount of input doesn't change once e.g. LZMA_FINISH has been
+	/// used.
+	size_t avail_in;
+
+	/// Indicates which lzma_action values are allowed by next.code.
+	bool supported_actions[4];
+
+	/// If true, lzma_code will return LZMA_BUF_ERROR if no progress was
+	/// made (no input consumed and no output produced by next.code).
+	bool allow_buf_error;
+};
+
+
+/// Allocates memory
+extern void *lzma_alloc(size_t size, lzma_allocator *allocator)
+		lzma_attribute((__malloc__)) lzma_attr_alloc_size(1);
+
+/// Frees memory
+extern void lzma_free(void *ptr, lzma_allocator *allocator);
+
+
+/// Allocates strm->internal if it is NULL, and initializes *strm and
+/// strm->internal. This function is only called via lzma_next_strm_init2 macro.
+extern lzma_ret lzma_strm_init(lzma_stream *strm);
+
+/// Initializes the next filter in the chain, if any. This takes care of
+/// freeing the memory of previously initialized filter if it is different
+/// than the filter being initialized now. This way the actual filter
+/// initialization functions don't need to use lzma_next_coder_init macro.
+extern lzma_ret lzma_next_filter_init(lzma_next_coder *next,
+		lzma_allocator *allocator, const lzma_filter_info *filters);
+
+/// Update the next filter in the chain, if any. This checks that
+/// the application is not trying to change the Filter IDs.
+extern lzma_ret lzma_next_filter_update(
+		lzma_next_coder *next, lzma_allocator *allocator,
+		const lzma_filter *reversed_filters);
+
+/// Frees the memory allocated for next->coder either using next->end or,
+/// if next->end is NULL, using lzma_free.
+extern void lzma_next_end(lzma_next_coder *next, lzma_allocator *allocator);
+
+
+/// Copy as much data as possible from in[] to out[] and update *in_pos
+/// and *out_pos accordingly. Returns the number of bytes copied.
+extern size_t lzma_bufcpy(const uint8_t *LZMA_RESTRICT in, size_t *LZMA_RESTRICT in_pos,
+		size_t in_size, uint8_t *LZMA_RESTRICT out,
+		size_t *LZMA_RESTRICT out_pos, size_t out_size);
+
+
+/// \brief      Return if expression doesn't evaluate to LZMA_OK
+///
+/// There are several situations where we want to return immediately
+/// with the value of expr if it isn't LZMA_OK. This macro shortens
+/// the code a little.
+#define return_if_error(expr) \
+do { \
+	const lzma_ret ret_ = (expr); \
+	if (ret_ != LZMA_OK) \
+		return ret_; \
+} while (0)
+
+
+/// If next isn't already initialized, free the previous coder. Then mark
+/// that next is _possibly_ initialized for the coder using this macro.
+/// "Possibly" means that if e.g. allocation of next->coder fails, the
+/// structure isn't actually initialized for this coder, but leaving
+/// next->init to func is still OK.
+#define lzma_next_coder_init(func, next, allocator) \
+do { \
+	if ((uintptr_t)(func) != (next)->init) \
+		lzma_next_end(next, allocator); \
+	(next)->init = (uintptr_t)(func); \
+} while (0)
+
+
+/// Initializes lzma_strm and calls func() to initialize strm->internal->next.
+/// (The function being called will use lzma_next_coder_init()). If
+/// initialization fails, memory that wasn't freed by func() is freed
+/// along strm->internal.
+#define lzma_next_strm_init1(func, strm, arg1) \
+do { \
+    lzma_ret ret_; \
+    return_if_error(lzma_strm_init(strm)); \
+    ret_ = func(&(strm)->internal->next, (strm)->allocator, arg1); \
+    if (ret_ != LZMA_OK) { \
+        lzma_end(strm); \
+        return ret_; \
+    } \
+} while (0)
+
+#define lzma_next_strm_init2(func, strm, arg1, arg2) \
+do { \
+    lzma_ret ret_; \
+    return_if_error(lzma_strm_init(strm)); \
+    ret_ = func(&(strm)->internal->next, (strm)->allocator, arg1, arg2); \
+    if (ret_ != LZMA_OK) { \
+        lzma_end(strm); \
+        return ret_; \
+    } \
+} while (0)
+
+#define lzma_next_strm_init3(func, strm, arg1, arg2, arg3) \
+do { \
+    lzma_ret ret_; \
+    return_if_error(lzma_strm_init(strm)); \
+    ret_ = func(&(strm)->internal->next, (strm)->allocator, arg1, arg2, arg3); \
+    if (ret_ != LZMA_OK) { \
+        lzma_end(strm); \
+        return ret_; \
+    } \
+} while (0)
+
+#endif
diff --git a/Utilities/cmliblzma/liblzma/common/easy_buffer_encoder.c b/Utilities/cmliblzma/liblzma/common/easy_buffer_encoder.c
new file mode 100644
index 0000000..c4be34c
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/easy_buffer_encoder.c
@@ -0,0 +1,27 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       easy_buffer_encoder.c
+/// \brief      Easy single-call .xz Stream encoder
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "easy_preset.h"
+
+
+extern LZMA_API(lzma_ret)
+lzma_easy_buffer_encode(uint32_t preset, lzma_check check,
+		lzma_allocator *allocator, const uint8_t *in, size_t in_size,
+		uint8_t *out, size_t *out_pos, size_t out_size)
+{
+	lzma_options_easy opt_easy;
+	if (lzma_easy_preset(&opt_easy, preset))
+		return LZMA_OPTIONS_ERROR;
+
+	return lzma_stream_buffer_encode(opt_easy.filters, check,
+			allocator, in, in_size, out, out_pos, out_size);
+}
diff --git a/Utilities/cmliblzma/liblzma/common/easy_decoder_memusage.c b/Utilities/cmliblzma/liblzma/common/easy_decoder_memusage.c
new file mode 100644
index 0000000..20bcd5b
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/easy_decoder_memusage.c
@@ -0,0 +1,24 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       easy_decoder_memusage.c
+/// \brief      Decoder memory usage calculation to match easy encoder presets
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "easy_preset.h"
+
+
+extern LZMA_API(uint64_t)
+lzma_easy_decoder_memusage(uint32_t preset)
+{
+	lzma_options_easy opt_easy;
+	if (lzma_easy_preset(&opt_easy, preset))
+		return UINT32_MAX;
+
+	return lzma_raw_decoder_memusage(opt_easy.filters);
+}
diff --git a/Utilities/cmliblzma/liblzma/common/easy_encoder.c b/Utilities/cmliblzma/liblzma/common/easy_encoder.c
new file mode 100644
index 0000000..d13ccd7
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/easy_encoder.c
@@ -0,0 +1,25 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       easy_encoder.c
+/// \brief      Easy .xz Stream encoder initialization
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "easy_preset.h"
+#include "stream_encoder.h"
+
+
+extern LZMA_API(lzma_ret)
+lzma_easy_encoder(lzma_stream *strm, uint32_t preset, lzma_check check)
+{
+	lzma_options_easy opt_easy;
+	if (lzma_easy_preset(&opt_easy, preset))
+		return LZMA_OPTIONS_ERROR;
+
+	return lzma_stream_encoder(strm, opt_easy.filters, check);
+}
diff --git a/Utilities/cmliblzma/liblzma/common/easy_encoder_memusage.c b/Utilities/cmliblzma/liblzma/common/easy_encoder_memusage.c
new file mode 100644
index 0000000..e910575
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/easy_encoder_memusage.c
@@ -0,0 +1,24 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       easy_encoder_memusage.c
+/// \brief      Easy .xz Stream encoder memory usage calculation
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "easy_preset.h"
+
+
+extern LZMA_API(uint64_t)
+lzma_easy_encoder_memusage(uint32_t preset)
+{
+	lzma_options_easy opt_easy;
+	if (lzma_easy_preset(&opt_easy, preset))
+		return UINT32_MAX;
+
+	return lzma_raw_encoder_memusage(opt_easy.filters);
+}
diff --git a/Utilities/cmliblzma/liblzma/common/easy_preset.c b/Utilities/cmliblzma/liblzma/common/easy_preset.c
new file mode 100644
index 0000000..2f98598
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/easy_preset.c
@@ -0,0 +1,27 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       easy_preset.c
+/// \brief      Preset handling for easy encoder and decoder
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "easy_preset.h"
+
+
+extern bool
+lzma_easy_preset(lzma_options_easy *opt_easy, uint32_t preset)
+{
+	if (lzma_lzma_preset(&opt_easy->opt_lzma, preset))
+		return true;
+
+	opt_easy->filters[0].id = LZMA_FILTER_LZMA2;
+	opt_easy->filters[0].options = &opt_easy->opt_lzma;
+	opt_easy->filters[1].id = LZMA_VLI_UNKNOWN;
+
+	return false;
+}
diff --git a/Utilities/cmliblzma/liblzma/common/easy_preset.h b/Utilities/cmliblzma/liblzma/common/easy_preset.h
new file mode 100644
index 0000000..382ade8
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/easy_preset.h
@@ -0,0 +1,32 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       easy_preset.h
+/// \brief      Preset handling for easy encoder and decoder
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "common.h"
+
+
+typedef struct {
+	/// We need to keep the filters array available in case
+	/// LZMA_FULL_FLUSH is used.
+	lzma_filter filters[LZMA_FILTERS_MAX + 1];
+
+	/// Options for LZMA2
+	lzma_options_lzma opt_lzma;
+
+	// Options for more filters can be added later, so this struct
+	// is not ready to be put into the public API.
+
+} lzma_options_easy;
+
+
+/// Set *easy to the settings given by the preset. Returns true on error,
+/// false on success.
+extern bool lzma_easy_preset(lzma_options_easy *easy, uint32_t preset);
diff --git a/Utilities/cmliblzma/liblzma/common/filter_buffer_decoder.c b/Utilities/cmliblzma/liblzma/common/filter_buffer_decoder.c
new file mode 100644
index 0000000..65665c1
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/filter_buffer_decoder.c
@@ -0,0 +1,91 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       filter_buffer_decoder.c
+/// \brief      Single-call raw decoding
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "filter_decoder.h"
+
+
+extern LZMA_API(lzma_ret)
+lzma_raw_buffer_decode(const lzma_filter *filters, lzma_allocator *allocator,
+		const uint8_t *in, size_t *in_pos, size_t in_size,
+		uint8_t *out, size_t *out_pos, size_t out_size)
+{
+	lzma_next_coder next = LZMA_NEXT_CODER_INIT;
+	size_t in_start;
+	size_t out_start;
+	lzma_ret ret;
+
+	// Validate what isn't validated later in filter_common.c.
+	if (in == NULL || in_pos == NULL || *in_pos > in_size || out == NULL
+			|| out_pos == NULL || *out_pos > out_size)
+		return LZMA_PROG_ERROR;
+
+	// Initialize the decoer.
+	return_if_error(lzma_raw_decoder_init(&next, allocator, filters));
+
+	// Store the positions so that we can restore them if something
+	// goes wrong.
+	in_start = *in_pos;
+	out_start = *out_pos;
+
+	// Do the actual decoding and free decoder's memory.
+	ret = next.code(next.coder, allocator, in, in_pos, in_size,
+			out, out_pos, out_size, LZMA_FINISH);
+
+	if (ret == LZMA_STREAM_END) {
+		ret = LZMA_OK;
+	} else {
+		if (ret == LZMA_OK) {
+			// Either the input was truncated or the
+			// output buffer was too small.
+			assert(*in_pos == in_size || *out_pos == out_size);
+
+			if (*in_pos != in_size) {
+				// Since input wasn't consumed completely,
+				// the output buffer became full and is
+				// too small.
+				ret = LZMA_BUF_ERROR;
+
+			} else if (*out_pos != out_size) {
+				// Since output didn't became full, the input
+				// has to be truncated.
+				ret = LZMA_DATA_ERROR;
+
+			} else {
+				// All the input was consumed and output
+				// buffer is full. Now we don't immediately
+				// know the reason for the error. Try
+				// decoding one more byte. If it succeeds,
+				// then the output buffer was too small. If
+				// we cannot get a new output byte, the input
+				// is truncated.
+				uint8_t tmp[1];
+				size_t tmp_pos = 0;
+				(void)next.code(next.coder, allocator,
+						in, in_pos, in_size,
+						tmp, &tmp_pos, 1, LZMA_FINISH);
+
+				if (tmp_pos == 1)
+					ret = LZMA_BUF_ERROR;
+				else
+					ret = LZMA_DATA_ERROR;
+			}
+		}
+
+		// Restore the positions.
+		*in_pos = in_start;
+		*out_pos = out_start;
+	}
+
+	lzma_next_end(&next, allocator);
+
+	return ret;
+}
diff --git a/Utilities/cmliblzma/liblzma/common/filter_buffer_encoder.c b/Utilities/cmliblzma/liblzma/common/filter_buffer_encoder.c
new file mode 100644
index 0000000..b23329f
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/filter_buffer_encoder.c
@@ -0,0 +1,57 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       filter_buffer_encoder.c
+/// \brief      Single-call raw encoding
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "filter_encoder.h"
+
+
+extern LZMA_API(lzma_ret)
+lzma_raw_buffer_encode(const lzma_filter *filters, lzma_allocator *allocator,
+		const uint8_t *in, size_t in_size, uint8_t *out,
+		size_t *out_pos, size_t out_size)
+{
+	lzma_next_coder next = LZMA_NEXT_CODER_INIT;
+	size_t out_start;
+	size_t in_pos = 0;
+	lzma_ret ret;
+
+	// Validate what isn't validated later in filter_common.c.
+	if ((in == NULL && in_size != 0) || out == NULL
+			|| out_pos == NULL || *out_pos > out_size)
+		return LZMA_PROG_ERROR;
+
+	// Initialize the encoder
+	return_if_error(lzma_raw_encoder_init(&next, allocator, filters));
+
+	// Store the output position so that we can restore it if
+	// something goes wrong.
+	out_start = *out_pos;
+
+	// Do the actual encoding and free coder's memory.
+	ret = next.code(next.coder, allocator, in, &in_pos, in_size,
+			out, out_pos, out_size, LZMA_FINISH);
+	lzma_next_end(&next, allocator);
+
+	if (ret == LZMA_STREAM_END) {
+		ret = LZMA_OK;
+	} else {
+		if (ret == LZMA_OK) {
+			// Output buffer was too small.
+			assert(*out_pos == out_size);
+			ret = LZMA_BUF_ERROR;
+		}
+
+		// Restore the output position.
+		*out_pos = out_start;
+	}
+
+	return ret;
+}
diff --git a/Utilities/cmliblzma/liblzma/common/filter_common.c b/Utilities/cmliblzma/liblzma/common/filter_common.c
new file mode 100644
index 0000000..d2b9e08
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/filter_common.c
@@ -0,0 +1,342 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       filter_common.c
+/// \brief      Filter-specific stuff common for both encoder and decoder
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "filter_common.h"
+
+
+static const struct {
+	/// Filter ID
+	lzma_vli id;
+
+	/// Size of the filter-specific options structure
+	size_t options_size;
+
+	/// True if it is OK to use this filter as non-last filter in
+	/// the chain.
+	bool non_last_ok;
+
+	/// True if it is OK to use this filter as the last filter in
+	/// the chain.
+	bool last_ok;
+
+	/// True if the filter may change the size of the data (that is, the
+	/// amount of encoded output can be different than the amount of
+	/// uncompressed input).
+	bool changes_size;
+
+} features[] = {
+#if defined (HAVE_ENCODER_LZMA1) || defined(HAVE_DECODER_LZMA1)
+	{
+		LZMA_FILTER_LZMA1,
+		sizeof(lzma_options_lzma),
+		false,
+		true,
+		true,
+	},
+#endif
+#if defined(HAVE_ENCODER_LZMA2) || defined(HAVE_DECODER_LZMA2)
+	{
+		LZMA_FILTER_LZMA2,
+		sizeof(lzma_options_lzma),
+		false,
+		true,
+		true,
+	},
+#endif
+#if defined(HAVE_ENCODER_X86) || defined(HAVE_DECODER_X86)
+	{
+		LZMA_FILTER_X86,
+		sizeof(lzma_options_bcj),
+		true,
+		false,
+		false,
+	},
+#endif
+#if defined(HAVE_ENCODER_POWERPC) || defined(HAVE_DECODER_POWERPC)
+	{
+		LZMA_FILTER_POWERPC,
+		sizeof(lzma_options_bcj),
+		true,
+		false,
+		false,
+	},
+#endif
+#if defined(HAVE_ENCODER_IA64) || defined(HAVE_DECODER_IA64)
+	{
+		LZMA_FILTER_IA64,
+		sizeof(lzma_options_bcj),
+		true,
+		false,
+		false,
+	},
+#endif
+#if defined(HAVE_ENCODER_ARM) || defined(HAVE_DECODER_ARM)
+	{
+		LZMA_FILTER_ARM,
+		sizeof(lzma_options_bcj),
+		true,
+		false,
+		false,
+	},
+#endif
+#if defined(HAVE_ENCODER_ARMTHUMB) || defined(HAVE_DECODER_ARMTHUMB)
+	{
+		LZMA_FILTER_ARMTHUMB,
+		sizeof(lzma_options_bcj),
+		true,
+		false,
+		false,
+	},
+#endif
+#if defined(HAVE_ENCODER_SPARC) || defined(HAVE_DECODER_SPARC)
+	{
+		LZMA_FILTER_SPARC,
+		sizeof(lzma_options_bcj),
+		true,
+		false,
+		false,
+	},
+#endif
+#if defined(HAVE_ENCODER_DELTA) || defined(HAVE_DECODER_DELTA)
+	{
+		LZMA_FILTER_DELTA,
+		sizeof(lzma_options_delta),
+		true,
+		false,
+		false,
+	},
+#endif
+	{
+		LZMA_VLI_UNKNOWN
+	}
+};
+
+
+extern LZMA_API(lzma_ret)
+lzma_filters_copy(const lzma_filter *src, lzma_filter *dest,
+		lzma_allocator *allocator)
+{
+	size_t i;
+	lzma_ret ret;
+
+	if (src == NULL || dest == NULL)
+		return LZMA_PROG_ERROR;
+
+	for (i = 0; src[i].id != LZMA_VLI_UNKNOWN; ++i) {
+		// There must be a maximum of four filters plus
+		// the array terminator.
+		if (i == LZMA_FILTERS_MAX) {
+			ret = LZMA_OPTIONS_ERROR;
+			goto error;
+		}
+
+		dest[i].id = src[i].id;
+
+		if (src[i].options == NULL) {
+			dest[i].options = NULL;
+		} else {
+			// See if the filter is supported only when the
+			// options is not NULL. This might be convenient
+			// sometimes if the app is actually copying only
+			// a partial filter chain with a place holder ID.
+			//
+			// When options is not NULL, the Filter ID must be
+			// supported by us, because otherwise we don't know
+			// how big the options are.
+			size_t j;
+			for (j = 0; src[i].id != features[j].id; ++j) {
+				if (features[j].id == LZMA_VLI_UNKNOWN) {
+					ret = LZMA_OPTIONS_ERROR;
+					goto error;
+				}
+			}
+
+			// Allocate and copy the options.
+			dest[i].options = lzma_alloc(features[j].options_size,
+					allocator);
+			if (dest[i].options == NULL) {
+				ret = LZMA_MEM_ERROR;
+				goto error;
+			}
+
+			memcpy(dest[i].options, src[i].options,
+					features[j].options_size);
+		}
+	}
+
+	// Terminate the filter array.
+	assert(i <= LZMA_FILTERS_MAX + 1);
+	dest[i].id = LZMA_VLI_UNKNOWN;
+	dest[i].options = NULL;
+
+	return LZMA_OK;
+
+error:
+	// Free the options which we have already allocated.
+	while (i-- > 0) {
+		lzma_free(dest[i].options, allocator);
+		dest[i].options = NULL;
+	}
+
+	return ret;
+}
+
+
+static lzma_ret
+validate_chain(const lzma_filter *filters, size_t *count)
+{
+	// Number of non-last filters that may change the size of the data
+	// significantly (that is, more than 1-2 % or so).
+	size_t changes_size_count = 0;
+
+	// True if it is OK to add a new filter after the current filter.
+	bool non_last_ok = true;
+
+	// True if the last filter in the given chain is actually usable as
+	// the last filter. Only filters that support embedding End of Payload
+	// Marker can be used as the last filter in the chain.
+	bool last_ok = false;
+
+	size_t i = 0;
+
+	// There must be at least one filter.
+	if (filters == NULL || filters[0].id == LZMA_VLI_UNKNOWN)
+		return LZMA_PROG_ERROR;
+
+	do {
+		size_t j;
+		for (j = 0; filters[i].id != features[j].id; ++j)
+			if (features[j].id == LZMA_VLI_UNKNOWN)
+				return LZMA_OPTIONS_ERROR;
+
+		// If the previous filter in the chain cannot be a non-last
+		// filter, the chain is invalid.
+		if (!non_last_ok)
+			return LZMA_OPTIONS_ERROR;
+
+		non_last_ok = features[j].non_last_ok;
+		last_ok = features[j].last_ok;
+		changes_size_count += features[j].changes_size;
+
+	} while (filters[++i].id != LZMA_VLI_UNKNOWN);
+
+	// There must be 1-4 filters. The last filter must be usable as
+	// the last filter in the chain. A maximum of three filters are
+	// allowed to change the size of the data.
+	if (i > LZMA_FILTERS_MAX || !last_ok || changes_size_count > 3)
+		return LZMA_OPTIONS_ERROR;
+
+	*count = i;
+	return LZMA_OK;
+}
+
+
+extern lzma_ret
+lzma_raw_coder_init(lzma_next_coder *next, lzma_allocator *allocator,
+		const lzma_filter *options,
+		lzma_filter_find coder_find, bool is_encoder)
+{
+	lzma_filter_info filters[LZMA_FILTERS_MAX + 1];
+	size_t count;
+	size_t i;
+	lzma_ret ret;
+
+	// Do some basic validation and get the number of filters.
+	return_if_error(validate_chain(options, &count));
+
+	// Set the filter functions and copy the options pointer.
+	if (is_encoder) {
+		for (i = 0; i < count; ++i) {
+			// The order of the filters is reversed in the
+			// encoder. It allows more efficient handling
+			// of the uncompressed data.
+			const size_t j = count - i - 1;
+
+			const lzma_filter_coder *const fc
+					= coder_find(options[i].id);
+			if (fc == NULL || fc->init == NULL)
+				return LZMA_OPTIONS_ERROR;
+
+			filters[j].id = options[i].id;
+			filters[j].init = fc->init;
+			filters[j].options = options[i].options;
+		}
+	} else {
+		for (i = 0; i < count; ++i) {
+			const lzma_filter_coder *const fc
+					= coder_find(options[i].id);
+			if (fc == NULL || fc->init == NULL)
+				return LZMA_OPTIONS_ERROR;
+
+			filters[i].id = options[i].id;
+			filters[i].init = fc->init;
+			filters[i].options = options[i].options;
+		}
+	}
+
+	// Terminate the array.
+	filters[count].id = LZMA_VLI_UNKNOWN;
+	filters[count].init = NULL;
+
+	// Initialize the filters.
+	ret = lzma_next_filter_init(next, allocator, filters);
+	if (ret != LZMA_OK)
+		lzma_next_end(next, allocator);
+
+	return ret;
+}
+
+
+extern uint64_t
+lzma_raw_coder_memusage(lzma_filter_find coder_find,
+		const lzma_filter *filters)
+{
+	uint64_t total = 0;
+	size_t i = 0;
+
+	// The chain has to have at least one filter.
+	{
+		size_t tmp;
+		if (validate_chain(filters, &tmp) != LZMA_OK)
+			return UINT64_MAX;
+	}
+
+	do {
+		const lzma_filter_coder *const fc
+				 = coder_find(filters[i].id);
+		if (fc == NULL)
+			return UINT64_MAX; // Unsupported Filter ID
+
+		if (fc->memusage == NULL) {
+			// This filter doesn't have a function to calculate
+			// the memory usage and validate the options. Such
+			// filters need only little memory, so we use 1 KiB
+			// as a good estimate. They also accept all possible
+			// options, so there's no need to worry about lack
+			// of validation.
+			total += 1024;
+		} else {
+			// Call the filter-specific memory usage calculation
+			// function.
+			const uint64_t usage
+					= fc->memusage(filters[i].options);
+			if (usage == UINT64_MAX)
+				return UINT64_MAX; // Invalid options
+
+			total += usage;
+		}
+	} while (filters[++i].id != LZMA_VLI_UNKNOWN);
+
+	// Add some fixed amount of extra. It's to compensate memory usage
+	// of Stream, Block etc. coders, malloc() overhead, stack etc.
+	return total + LZMA_MEMUSAGE_BASE;
+}
diff --git a/Utilities/cmliblzma/liblzma/common/filter_common.h b/Utilities/cmliblzma/liblzma/common/filter_common.h
new file mode 100644
index 0000000..cd61fc0
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/filter_common.h
@@ -0,0 +1,48 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       filter_common.c
+/// \brief      Filter-specific stuff common for both encoder and decoder
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#ifndef LZMA_FILTER_COMMON_H
+#define LZMA_FILTER_COMMON_H
+
+#include "common.h"
+
+
+/// Both lzma_filter_encoder and lzma_filter_decoder begin with these members.
+typedef struct {
+	/// Filter ID
+	lzma_vli id;
+
+	/// Initializes the filter encoder and calls lzma_next_filter_init()
+	/// for filters + 1.
+	lzma_init_function init;
+
+	/// Calculates memory usage of the encoder. If the options are
+	/// invalid, UINT64_MAX is returned.
+	uint64_t (*memusage)(const void *options);
+
+} lzma_filter_coder;
+
+
+typedef const lzma_filter_coder *(*lzma_filter_find)(lzma_vli id);
+
+
+extern lzma_ret lzma_raw_coder_init(
+		lzma_next_coder *next, lzma_allocator *allocator,
+		const lzma_filter *filters,
+		lzma_filter_find coder_find, bool is_encoder);
+
+
+extern uint64_t lzma_raw_coder_memusage(lzma_filter_find coder_find,
+		const lzma_filter *filters);
+
+
+#endif
diff --git a/Utilities/cmliblzma/liblzma/common/filter_decoder.c b/Utilities/cmliblzma/liblzma/common/filter_decoder.c
new file mode 100644
index 0000000..cce2b30
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/filter_decoder.c
@@ -0,0 +1,185 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       filter_decoder.c
+/// \brief      Filter ID mapping to filter-specific functions
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "filter_decoder.h"
+#include "filter_common.h"
+#include "lzma_decoder.h"
+#include "lzma2_decoder.h"
+#include "simple_decoder.h"
+#include "delta_decoder.h"
+
+
+typedef struct {
+	/// Filter ID
+	lzma_vli id;
+
+	/// Initializes the filter encoder and calls lzma_next_filter_init()
+	/// for filters + 1.
+	lzma_init_function init;
+
+	/// Calculates memory usage of the encoder. If the options are
+	/// invalid, UINT64_MAX is returned.
+	uint64_t (*memusage)(const void *options);
+
+	/// Decodes Filter Properties.
+	///
+	/// \return     - LZMA_OK: Properties decoded successfully.
+	///             - LZMA_OPTIONS_ERROR: Unsupported properties
+	///             - LZMA_MEM_ERROR: Memory allocation failed.
+	lzma_ret (*props_decode)(void **options, lzma_allocator *allocator,
+			const uint8_t *props, size_t props_size);
+
+} lzma_filter_decoder;
+
+
+static const lzma_filter_decoder decoders[] = {
+#ifdef HAVE_DECODER_LZMA1
+	{
+		LZMA_FILTER_LZMA1,
+		&lzma_lzma_decoder_init,
+		&lzma_lzma_decoder_memusage,
+		&lzma_lzma_props_decode,
+	},
+#endif
+#ifdef HAVE_DECODER_LZMA2
+	{
+		LZMA_FILTER_LZMA2,
+		&lzma_lzma2_decoder_init,
+		&lzma_lzma2_decoder_memusage,
+		&lzma_lzma2_props_decode,
+	},
+#endif
+#ifdef HAVE_DECODER_X86
+	{
+		LZMA_FILTER_X86,
+		&lzma_simple_x86_decoder_init,
+		NULL,
+		&lzma_simple_props_decode,
+	},
+#endif
+#ifdef HAVE_DECODER_POWERPC
+	{
+		LZMA_FILTER_POWERPC,
+		&lzma_simple_powerpc_decoder_init,
+		NULL,
+		&lzma_simple_props_decode,
+	},
+#endif
+#ifdef HAVE_DECODER_IA64
+	{
+		LZMA_FILTER_IA64,
+		&lzma_simple_ia64_decoder_init,
+		NULL,
+		&lzma_simple_props_decode,
+	},
+#endif
+#ifdef HAVE_DECODER_ARM
+	{
+		LZMA_FILTER_ARM,
+		&lzma_simple_arm_decoder_init,
+		NULL,
+		&lzma_simple_props_decode,
+	},
+#endif
+#ifdef HAVE_DECODER_ARMTHUMB
+	{
+		LZMA_FILTER_ARMTHUMB,
+		&lzma_simple_armthumb_decoder_init,
+		NULL,
+		&lzma_simple_props_decode,
+	},
+#endif
+#ifdef HAVE_DECODER_SPARC
+	{
+		LZMA_FILTER_SPARC,
+		&lzma_simple_sparc_decoder_init,
+		NULL,
+		&lzma_simple_props_decode,
+	},
+#endif
+#ifdef HAVE_DECODER_DELTA
+	{
+		LZMA_FILTER_DELTA,
+		&lzma_delta_decoder_init,
+		&lzma_delta_coder_memusage,
+		&lzma_delta_props_decode,
+	},
+#endif
+};
+
+
+static const lzma_filter_decoder *
+decoder_find(lzma_vli id)
+{
+	size_t i;
+	for (i = 0; i < ARRAY_SIZE(decoders); ++i)
+		if (decoders[i].id == id)
+			return decoders + i;
+
+	return NULL;
+}
+
+
+extern LZMA_API(lzma_bool)
+lzma_filter_decoder_is_supported(lzma_vli id)
+{
+	return decoder_find(id) != NULL;
+}
+
+
+extern lzma_ret
+lzma_raw_decoder_init(lzma_next_coder *next, lzma_allocator *allocator,
+		const lzma_filter *options)
+{
+	return lzma_raw_coder_init(next, allocator,
+			options, (lzma_filter_find)(&decoder_find), false);
+}
+
+
+extern LZMA_API(lzma_ret)
+lzma_raw_decoder(lzma_stream *strm, const lzma_filter *options)
+{
+	lzma_next_strm_init1(lzma_raw_decoder_init, strm, options);
+
+	strm->internal->supported_actions[LZMA_RUN] = true;
+	strm->internal->supported_actions[LZMA_FINISH] = true;
+
+	return LZMA_OK;
+}
+
+
+extern LZMA_API(uint64_t)
+lzma_raw_decoder_memusage(const lzma_filter *filters)
+{
+	return lzma_raw_coder_memusage(
+			(lzma_filter_find)(&decoder_find), filters);
+}
+
+
+extern LZMA_API(lzma_ret)
+lzma_properties_decode(lzma_filter *filter, lzma_allocator *allocator,
+		const uint8_t *props, size_t props_size)
+{
+	const lzma_filter_decoder *const fd = decoder_find(filter->id);
+
+	// Make it always NULL so that the caller can always safely free() it.
+	filter->options = NULL;
+
+	if (fd == NULL)
+		return LZMA_OPTIONS_ERROR;
+
+	if (fd->props_decode == NULL)
+		return props_size == 0 ? LZMA_OK : LZMA_OPTIONS_ERROR;
+
+	return fd->props_decode(
+			&filter->options, allocator, props, props_size);
+}
diff --git a/Utilities/cmliblzma/liblzma/common/filter_decoder.h b/Utilities/cmliblzma/liblzma/common/filter_decoder.h
new file mode 100644
index 0000000..d5c68bd
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/filter_decoder.h
@@ -0,0 +1,23 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       filter_decoder.c
+/// \brief      Filter ID mapping to filter-specific functions
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#ifndef LZMA_FILTER_DECODER_H
+#define LZMA_FILTER_DECODER_H
+
+#include "common.h"
+
+
+extern lzma_ret lzma_raw_decoder_init(
+		lzma_next_coder *next, lzma_allocator *allocator,
+		const lzma_filter *options);
+
+#endif
diff --git a/Utilities/cmliblzma/liblzma/common/filter_encoder.c b/Utilities/cmliblzma/liblzma/common/filter_encoder.c
new file mode 100644
index 0000000..9fdb100
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/filter_encoder.c
@@ -0,0 +1,297 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       filter_decoder.c
+/// \brief      Filter ID mapping to filter-specific functions
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "filter_encoder.h"
+#include "filter_common.h"
+#include "lzma_encoder.h"
+#include "lzma2_encoder.h"
+#include "simple_encoder.h"
+#include "delta_encoder.h"
+
+
+typedef struct {
+	/// Filter ID
+	lzma_vli id;
+
+	/// Initializes the filter encoder and calls lzma_next_filter_init()
+	/// for filters + 1.
+	lzma_init_function init;
+
+	/// Calculates memory usage of the encoder. If the options are
+	/// invalid, UINT64_MAX is returned.
+	uint64_t (*memusage)(const void *options);
+
+	/// Calculates the minimum sane size for Blocks (or other types of
+	/// chunks) to which the input data can be split to make
+	/// multithreaded encoding possible. If this is NULL, it is assumed
+	/// that the encoder is fast enough with single thread.
+	lzma_vli (*chunk_size)(const void *options);
+
+	/// Tells the size of the Filter Properties field. If options are
+	/// invalid, UINT32_MAX is returned. If this is NULL, props_size_fixed
+	/// is used.
+	lzma_ret (*props_size_get)(uint32_t *size, const void *options);
+	uint32_t props_size_fixed;
+
+	/// Encodes Filter Properties.
+	///
+	/// \return     - LZMA_OK: Properties encoded successfully.
+	///             - LZMA_OPTIONS_ERROR: Unsupported options
+	///             - LZMA_PROG_ERROR: Invalid options or not enough
+	///               output space
+	lzma_ret (*props_encode)(const void *options, uint8_t *out);
+
+} lzma_filter_encoder;
+
+
+static const lzma_filter_encoder encoders[] = {
+#ifdef HAVE_ENCODER_LZMA1
+	{
+		LZMA_FILTER_LZMA1,
+		&lzma_lzma_encoder_init,
+		&lzma_lzma_encoder_memusage,
+		NULL, // FIXME
+		NULL,
+		5,
+		&lzma_lzma_props_encode,
+	},
+#endif
+#ifdef HAVE_ENCODER_LZMA2
+	{
+		LZMA_FILTER_LZMA2,
+		&lzma_lzma2_encoder_init,
+		&lzma_lzma2_encoder_memusage,
+		NULL, // FIXME
+		NULL,
+		1,
+		&lzma_lzma2_props_encode,
+	},
+#endif
+#ifdef HAVE_ENCODER_X86
+	{
+		LZMA_FILTER_X86,
+		&lzma_simple_x86_encoder_init,
+		NULL,
+		NULL,
+		&lzma_simple_props_size,
+		0,
+		&lzma_simple_props_encode,
+	},
+#endif
+#ifdef HAVE_ENCODER_POWERPC
+	{
+		LZMA_FILTER_POWERPC,
+		&lzma_simple_powerpc_encoder_init,
+		NULL,
+		NULL,
+		&lzma_simple_props_size,
+		0,
+		&lzma_simple_props_encode,
+	},
+#endif
+#ifdef HAVE_ENCODER_IA64
+	{
+		LZMA_FILTER_IA64,
+		&lzma_simple_ia64_encoder_init,
+		NULL,
+		NULL,
+		&lzma_simple_props_size,
+		0,
+		&lzma_simple_props_encode,
+	},
+#endif
+#ifdef HAVE_ENCODER_ARM
+	{
+		LZMA_FILTER_ARM,
+		&lzma_simple_arm_encoder_init,
+		NULL,
+		NULL,
+		&lzma_simple_props_size,
+		0,
+		&lzma_simple_props_encode,
+	},
+#endif
+#ifdef HAVE_ENCODER_ARMTHUMB
+	{
+		LZMA_FILTER_ARMTHUMB,
+		&lzma_simple_armthumb_encoder_init,
+		NULL,
+		NULL,
+		&lzma_simple_props_size,
+		0,
+		&lzma_simple_props_encode,
+	},
+#endif
+#ifdef HAVE_ENCODER_SPARC
+	{
+		LZMA_FILTER_SPARC,
+		&lzma_simple_sparc_encoder_init,
+		NULL,
+		NULL,
+		&lzma_simple_props_size,
+		0,
+		&lzma_simple_props_encode,
+	},
+#endif
+#ifdef HAVE_ENCODER_DELTA
+	{
+		LZMA_FILTER_DELTA,
+		&lzma_delta_encoder_init,
+		&lzma_delta_coder_memusage,
+		NULL,
+		NULL,
+		1,
+		&lzma_delta_props_encode,
+	},
+#endif
+};
+
+
+static const lzma_filter_encoder *
+encoder_find(lzma_vli id)
+{
+	size_t i;
+	for (i = 0; i < ARRAY_SIZE(encoders); ++i)
+		if (encoders[i].id == id)
+			return encoders + i;
+
+	return NULL;
+}
+
+
+extern LZMA_API(lzma_bool)
+lzma_filter_encoder_is_supported(lzma_vli id)
+{
+	return encoder_find(id) != NULL;
+}
+
+
+extern LZMA_API(lzma_ret)
+lzma_filters_update(lzma_stream *strm, const lzma_filter *filters)
+{
+	size_t i;
+	size_t count = 1;
+	lzma_filter reversed_filters[LZMA_FILTERS_MAX + 1];
+
+	if (strm->internal->next.update == NULL)
+		return LZMA_PROG_ERROR;
+
+	// Validate the filter chain.
+	if (lzma_raw_encoder_memusage(filters) == UINT64_MAX)
+		return LZMA_OPTIONS_ERROR;
+
+	// The actual filter chain in the encoder is reversed. Some things
+	// still want the normal order chain, so we provide both.
+	while (filters[count].id != LZMA_VLI_UNKNOWN)
+		++count;
+
+	for (i = 0; i < count; ++i)
+		reversed_filters[count - i - 1] = filters[i];
+
+	reversed_filters[count].id = LZMA_VLI_UNKNOWN;
+
+	return strm->internal->next.update(strm->internal->next.coder,
+			strm->allocator, filters, reversed_filters);
+}
+
+
+extern lzma_ret
+lzma_raw_encoder_init(lzma_next_coder *next, lzma_allocator *allocator,
+		const lzma_filter *options)
+{
+	return lzma_raw_coder_init(next, allocator,
+			options, (lzma_filter_find)(&encoder_find), true);
+}
+
+
+extern LZMA_API(lzma_ret)
+lzma_raw_encoder(lzma_stream *strm, const lzma_filter *options)
+{
+	lzma_next_strm_init3(lzma_raw_coder_init, strm, options,
+			(lzma_filter_find)(&encoder_find), true);
+
+	strm->internal->supported_actions[LZMA_RUN] = true;
+	strm->internal->supported_actions[LZMA_SYNC_FLUSH] = true;
+	strm->internal->supported_actions[LZMA_FINISH] = true;
+
+	return LZMA_OK;
+}
+
+
+extern LZMA_API(uint64_t)
+lzma_raw_encoder_memusage(const lzma_filter *filters)
+{
+	return lzma_raw_coder_memusage(
+			(lzma_filter_find)(&encoder_find), filters);
+}
+
+
+/*
+extern LZMA_API(lzma_vli)
+lzma_chunk_size(const lzma_filter *filters)
+{
+	lzma_vli max = 0;
+
+	for (size_t i = 0; filters[i].id != LZMA_VLI_UNKNOWN; ++i) {
+		const lzma_filter_encoder *const fe
+				= encoder_find(filters[i].id);
+		if (fe->chunk_size != NULL) {
+			const lzma_vli size
+					= fe->chunk_size(filters[i].options);
+			if (size == LZMA_VLI_UNKNOWN)
+				return LZMA_VLI_UNKNOWN;
+
+			if (size > max)
+				max = size;
+		}
+	}
+
+	return max;
+}
+*/
+
+
+extern LZMA_API(lzma_ret)
+lzma_properties_size(uint32_t *size, const lzma_filter *filter)
+{
+	const lzma_filter_encoder *const fe = encoder_find(filter->id);
+	if (fe == NULL) {
+		// Unknown filter - if the Filter ID is a proper VLI,
+		// return LZMA_OPTIONS_ERROR instead of LZMA_PROG_ERROR,
+		// because it's possible that we just don't have support
+		// compiled in for the requested filter.
+		return filter->id <= LZMA_VLI_MAX
+				? LZMA_OPTIONS_ERROR : LZMA_PROG_ERROR;
+	}
+
+	if (fe->props_size_get == NULL) {
+		// No props_size_get() function, use props_size_fixed.
+		*size = fe->props_size_fixed;
+		return LZMA_OK;
+	}
+
+	return fe->props_size_get(size, filter->options);
+}
+
+
+extern LZMA_API(lzma_ret)
+lzma_properties_encode(const lzma_filter *filter, uint8_t *props)
+{
+	const lzma_filter_encoder *const fe = encoder_find(filter->id);
+	if (fe == NULL)
+		return LZMA_PROG_ERROR;
+
+	if (fe->props_encode == NULL)
+		return LZMA_OK;
+
+	return fe->props_encode(filter->options, props);
+}
diff --git a/Utilities/cmliblzma/liblzma/common/filter_encoder.h b/Utilities/cmliblzma/liblzma/common/filter_encoder.h
new file mode 100644
index 0000000..5bc137f
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/filter_encoder.h
@@ -0,0 +1,27 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       filter_encoder.c
+/// \brief      Filter ID mapping to filter-specific functions
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#ifndef LZMA_FILTER_ENCODER_H
+#define LZMA_FILTER_ENCODER_H
+
+#include "common.h"
+
+
+// FIXME: Might become a part of the public API once finished.
+// extern lzma_vli lzma_chunk_size(const lzma_filter *filters);
+
+
+extern lzma_ret lzma_raw_encoder_init(
+		lzma_next_coder *next, lzma_allocator *allocator,
+		const lzma_filter *filters);
+
+#endif
diff --git a/Utilities/cmliblzma/liblzma/common/filter_flags_decoder.c b/Utilities/cmliblzma/liblzma/common/filter_flags_decoder.c
new file mode 100644
index 0000000..aa2dbd5
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/filter_flags_decoder.c
@@ -0,0 +1,48 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       filter_flags_decoder.c
+/// \brief      Decodes a Filter Flags field
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "filter_decoder.h"
+
+
+extern LZMA_API(lzma_ret)
+lzma_filter_flags_decode(
+		lzma_filter *filter, lzma_allocator *allocator,
+		const uint8_t *in, size_t *in_pos, size_t in_size)
+{
+	lzma_vli props_size;
+	lzma_ret ret;
+	
+	// Set the pointer to NULL so the caller can always safely free it.
+	filter->options = NULL;
+
+	// Filter ID
+	return_if_error(lzma_vli_decode(&filter->id, NULL,
+			in, in_pos, in_size));
+
+	if (filter->id >= LZMA_FILTER_RESERVED_START)
+		return LZMA_DATA_ERROR;
+
+	// Size of Properties
+	return_if_error(lzma_vli_decode(&props_size, NULL,
+			in, in_pos, in_size));
+
+	// Filter Properties
+	if (in_size - *in_pos < props_size)
+		return LZMA_DATA_ERROR;
+
+	ret = lzma_properties_decode(
+			filter, allocator, in + *in_pos, props_size);
+
+	*in_pos += props_size;
+
+	return ret;
+}
diff --git a/Utilities/cmliblzma/liblzma/common/filter_flags_encoder.c b/Utilities/cmliblzma/liblzma/common/filter_flags_encoder.c
new file mode 100644
index 0000000..755c407
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/filter_flags_encoder.c
@@ -0,0 +1,57 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       filter_flags_encoder.c
+/// \brief      Decodes a Filter Flags field
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "filter_encoder.h"
+
+
+extern LZMA_API(lzma_ret)
+lzma_filter_flags_size(uint32_t *size, const lzma_filter *filter)
+{
+	if (filter->id >= LZMA_FILTER_RESERVED_START)
+		return LZMA_PROG_ERROR;
+
+	return_if_error(lzma_properties_size(size, filter));
+
+	*size += lzma_vli_size(filter->id) + lzma_vli_size(*size);
+
+	return LZMA_OK;
+}
+
+
+extern LZMA_API(lzma_ret)
+lzma_filter_flags_encode(const lzma_filter *filter,
+		uint8_t *out, size_t *out_pos, size_t out_size)
+{
+	uint32_t props_size;
+
+	// Filter ID
+	if (filter->id >= LZMA_FILTER_RESERVED_START)
+		return LZMA_PROG_ERROR;
+
+	return_if_error(lzma_vli_encode(filter->id, NULL,
+			out, out_pos, out_size));
+
+	// Size of Properties
+	return_if_error(lzma_properties_size(&props_size, filter));
+	return_if_error(lzma_vli_encode(props_size, NULL,
+			out, out_pos, out_size));
+
+	// Filter Properties
+	if (out_size - *out_pos < props_size)
+		return LZMA_PROG_ERROR;
+
+	return_if_error(lzma_properties_encode(filter, out + *out_pos));
+
+	*out_pos += props_size;
+
+	return LZMA_OK;
+}
diff --git a/Utilities/cmliblzma/liblzma/common/hardware_physmem.c b/Utilities/cmliblzma/liblzma/common/hardware_physmem.c
new file mode 100644
index 0000000..7405b65
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/hardware_physmem.c
@@ -0,0 +1,25 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       hardware_physmem.c
+/// \brief      Get the total amount of physical memory (RAM)
+//
+//  Author:     Jonathan Nieder
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "common.h"
+
+#include "tuklib_physmem.h"
+
+
+extern LZMA_API(uint64_t)
+lzma_physmem(void)
+{
+	// It is simpler to make lzma_physmem() a wrapper for
+	// tuklib_physmem() than to hack appropriate symbol visiblity
+	// support for the tuklib modules.
+	return tuklib_physmem();
+}
diff --git a/Utilities/cmliblzma/liblzma/common/index.c b/Utilities/cmliblzma/liblzma/common/index.c
new file mode 100644
index 0000000..26135d2
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/index.c
@@ -0,0 +1,1276 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       index.c
+/// \brief      Handling of .xz Indexes and some other Stream information
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "index.h"
+#include "stream_flags_common.h"
+
+
+/// \brief      How many Records to allocate at once
+///
+/// This should be big enough to avoid making lots of tiny allocations
+/// but small enough to avoid too much unused memory at once.
+#define INDEX_GROUP_SIZE 512
+
+
+/// \brief      How many Records can be allocated at once at maximum
+#define PREALLOC_MAX ((SIZE_MAX - sizeof(index_group)) / sizeof(index_record))
+
+
+/// \brief      Base structure for index_stream and index_group structures
+typedef struct index_tree_node_s index_tree_node;
+struct index_tree_node_s {
+	/// Uncompressed start offset of this Stream (relative to the
+	/// beginning of the file) or Block (relative to the beginning
+	/// of the Stream)
+	lzma_vli uncompressed_base;
+
+	/// Compressed start offset of this Stream or Block
+	lzma_vli compressed_base;
+
+	index_tree_node *parent;
+	index_tree_node *left;
+	index_tree_node *right;
+};
+
+
+/// \brief      AVL tree to hold index_stream or index_group structures
+typedef struct {
+	/// Root node
+	index_tree_node *root;
+
+	/// Leftmost node. Since the tree will be filled sequentially,
+	/// this won't change after the first node has been added to
+	/// the tree.
+	index_tree_node *leftmost;
+
+	/// The rightmost node in the tree. Since the tree is filled
+	/// sequentially, this is always the node where to add the new data.
+	index_tree_node *rightmost;
+
+	/// Number of nodes in the tree
+	uint32_t count;
+
+} index_tree;
+
+
+typedef struct {
+	lzma_vli uncompressed_sum;
+	lzma_vli unpadded_sum;
+} index_record;
+
+
+typedef struct {
+	/// Every Record group is part of index_stream.groups tree.
+	index_tree_node node;
+
+	/// Number of Blocks in this Stream before this group.
+	lzma_vli number_base;
+
+	/// Number of Records that can be put in records[].
+	size_t allocated;
+
+	/// Index of the last Record in use.
+	size_t last;
+
+	/// The sizes in this array are stored as cumulative sums relative
+	/// to the beginning of the Stream. This makes it possible to
+	/// use binary search in lzma_index_locate().
+	///
+	/// Note that the cumulative summing is done specially for
+	/// unpadded_sum: The previous value is rounded up to the next
+	/// multiple of four before adding the Unpadded Size of the new
+	/// Block. The total encoded size of the Blocks in the Stream
+	/// is records[last].unpadded_sum in the last Record group of
+	/// the Stream.
+	///
+	/// For example, if the Unpadded Sizes are 39, 57, and 81, the
+	/// stored values are 39, 97 (40 + 57), and 181 (100 + 181).
+	/// The total encoded size of these Blocks is 184.
+	///
+	/// This is a flexible array, because it makes easy to optimize
+	/// memory usage in case someone concatenates many Streams that
+	/// have only one or few Blocks.
+	index_record records[];
+
+} index_group;
+
+
+typedef struct {
+	/// Every index_stream is a node in the tree of Sreams.
+	index_tree_node node;
+
+	/// Number of this Stream (first one is 1)
+	uint32_t number;
+
+	/// Total number of Blocks before this Stream
+	lzma_vli block_number_base;
+
+	/// Record groups of this Stream are stored in a tree.
+	/// It's a T-tree with AVL-tree balancing. There are
+	/// INDEX_GROUP_SIZE Records per node by default.
+	/// This keeps the number of memory allocations reasonable
+	/// and finding a Record is fast.
+	index_tree groups;
+
+	/// Number of Records in this Stream
+	lzma_vli record_count;
+
+	/// Size of the List of Records field in this Stream. This is used
+	/// together with record_count to calculate the size of the Index
+	/// field and thus the total size of the Stream.
+	lzma_vli index_list_size;
+
+	/// Stream Flags of this Stream. This is meaningful only if
+	/// the Stream Flags have been told us with lzma_index_stream_flags().
+	/// Initially stream_flags.version is set to UINT32_MAX to indicate
+	/// that the Stream Flags are unknown.
+	lzma_stream_flags stream_flags;
+
+	/// Amount of Stream Padding after this Stream. This defaults to
+	/// zero and can be set with lzma_index_stream_padding().
+	lzma_vli stream_padding;
+
+} index_stream;
+
+
+struct lzma_index_s {
+	/// AVL-tree containing the Stream(s). Often there is just one
+	/// Stream, but using a tree keeps lookups fast even when there
+	/// are many concatenated Streams.
+	index_tree streams;
+
+	/// Uncompressed size of all the Blocks in the Stream(s)
+	lzma_vli uncompressed_size;
+
+	/// Total size of all the Blocks in the Stream(s)
+	lzma_vli total_size;
+
+	/// Total number of Records in all Streams in this lzma_index
+	lzma_vli record_count;
+
+	/// Size of the List of Records field if all the Streams in this
+	/// lzma_index were packed into a single Stream (makes it simpler to
+	/// take many .xz files and combine them into a single Stream).
+	///
+	/// This value together with record_count is needed to calculate
+	/// Backward Size that is stored into Stream Footer.
+	lzma_vli index_list_size;
+
+	/// How many Records to allocate at once in lzma_index_append().
+	/// This defaults to INDEX_GROUP_SIZE but can be overriden with
+	/// lzma_index_prealloc().
+	size_t prealloc;
+
+	/// Bitmask indicating what integrity check types have been used
+	/// as set by lzma_index_stream_flags(). The bit of the last Stream
+	/// is not included here, since it is possible to change it by
+	/// calling lzma_index_stream_flags() again.
+	uint32_t checks;
+};
+
+
+static void
+index_tree_init(index_tree *tree)
+{
+	tree->root = NULL;
+	tree->leftmost = NULL;
+	tree->rightmost = NULL;
+	tree->count = 0;
+	return;
+}
+
+
+/// Helper for index_tree_end()
+static void
+index_tree_node_end(index_tree_node *node, lzma_allocator *allocator,
+		void (*free_func)(void *node, lzma_allocator *allocator))
+{
+	// The tree won't ever be very huge, so recursion should be fine.
+	// 20 levels in the tree is likely quite a lot already in practice.
+	if (node->left != NULL)
+		index_tree_node_end(node->left, allocator, free_func);
+
+	if (node->right != NULL)
+		index_tree_node_end(node->right, allocator, free_func);
+
+	if (free_func != NULL)
+		free_func(node, allocator);
+
+	lzma_free(node, allocator);
+	return;
+}
+
+
+/// Free the meory allocated for a tree. If free_func is not NULL,
+/// it is called on each node before freeing the node. This is used
+/// to free the Record groups from each index_stream before freeing
+/// the index_stream itself.
+static void
+index_tree_end(index_tree *tree, lzma_allocator *allocator,
+		void (*free_func)(void *node, lzma_allocator *allocator))
+{
+	if (tree->root != NULL)
+		index_tree_node_end(tree->root, allocator, free_func);
+
+	return;
+}
+
+
+/// Add a new node to the tree. node->uncompressed_base and
+/// node->compressed_base must have been set by the caller already.
+static void
+index_tree_append(index_tree *tree, index_tree_node *node)
+{
+	uint32_t up;
+	node->parent = tree->rightmost;
+	node->left = NULL;
+	node->right = NULL;
+
+	++tree->count;
+
+	// Handle the special case of adding the first node.
+	if (tree->root == NULL) {
+		tree->root = node;
+		tree->leftmost = node;
+		tree->rightmost = node;
+		return;
+	}
+
+	// The tree is always filled sequentially.
+	assert(tree->rightmost->uncompressed_base <= node->uncompressed_base);
+	assert(tree->rightmost->compressed_base < node->compressed_base);
+
+	// Add the new node after the rightmost node. It's the correct
+	// place due to the reason above.
+	tree->rightmost->right = node;
+	tree->rightmost = node;
+
+	// Balance the AVL-tree if needed. We don't need to keep the balance
+	// factors in nodes, because we always fill the tree sequentially,
+	// and thus know the state of the tree just by looking at the node
+	// count. From the node count we can calculate how many steps to go
+	// up in the tree to find the rotation root.
+	up = tree->count ^ (UINT32_C(1) << bsr32(tree->count));
+	if (up != 0) {
+		index_tree_node *pivot;
+
+		// Locate the root node for the rotation.
+		up = ctz32(tree->count) + 2;
+		do {
+			node = node->parent;
+		} while (--up > 0);
+
+		// Rotate left using node as the rotation root.
+		pivot = node->right;
+
+		if (node->parent == NULL) {
+			tree->root = pivot;
+		} else {
+			assert(node->parent->right == node);
+			node->parent->right = pivot;
+		}
+
+		pivot->parent = node->parent;
+
+		node->right = pivot->left;
+		if (node->right != NULL)
+			node->right->parent = node;
+
+		pivot->left = node;
+		node->parent = pivot;
+	}
+
+	return;
+}
+
+
+/// Get the next node in the tree. Return NULL if there are no more nodes.
+static void *
+index_tree_next(const index_tree_node *node)
+{
+	if (node->right != NULL) {
+		node = node->right;
+		while (node->left != NULL)
+			node = node->left;
+
+		return (void *)(node);
+	}
+
+	while (node->parent != NULL && node->parent->right == node)
+		node = node->parent;
+
+	return (void *)(node->parent);
+}
+
+
+/// Locate a node that contains the given uncompressed offset. It is
+/// caller's job to check that target is not bigger than the uncompressed
+/// size of the tree (the last node would be returned in that case still).
+static void *
+index_tree_locate(const index_tree *tree, lzma_vli target)
+{
+	const index_tree_node *result = NULL;
+	const index_tree_node *node = tree->root;
+
+	assert(tree->leftmost == NULL
+			|| tree->leftmost->uncompressed_base == 0);
+
+	// Consecutive nodes may have the same uncompressed_base.
+	// We must pick the rightmost one.
+	while (node != NULL) {
+		if (node->uncompressed_base > target) {
+			node = node->left;
+		} else {
+			result = node;
+			node = node->right;
+		}
+	}
+
+	return (void *)(result);
+}
+
+
+/// Allocate and initialize a new Stream using the given base offsets.
+static index_stream *
+index_stream_init(lzma_vli compressed_base, lzma_vli uncompressed_base,
+		lzma_vli stream_number, lzma_vli block_number_base,
+		lzma_allocator *allocator)
+{
+	index_stream *s = lzma_alloc(sizeof(index_stream), allocator);
+	if (s == NULL)
+		return NULL;
+
+	s->node.uncompressed_base = uncompressed_base;
+	s->node.compressed_base = compressed_base;
+	s->node.parent = NULL;
+	s->node.left = NULL;
+	s->node.right = NULL;
+
+	s->number = stream_number;
+	s->block_number_base = block_number_base;
+
+	index_tree_init(&s->groups);
+
+	s->record_count = 0;
+	s->index_list_size = 0;
+	s->stream_flags.version = UINT32_MAX;
+	s->stream_padding = 0;
+
+	return s;
+}
+
+
+/// Free the memory allocated for a Stream and its Record groups.
+static void
+index_stream_end(void *node, lzma_allocator *allocator)
+{
+	index_stream *s = node;
+	index_tree_end(&s->groups, allocator, NULL);
+	return;
+}
+
+
+static lzma_index *
+index_init_plain(lzma_allocator *allocator)
+{
+	lzma_index *i = lzma_alloc(sizeof(lzma_index), allocator);
+	if (i != NULL) {
+		index_tree_init(&i->streams);
+		i->uncompressed_size = 0;
+		i->total_size = 0;
+		i->record_count = 0;
+		i->index_list_size = 0;
+		i->prealloc = INDEX_GROUP_SIZE;
+		i->checks = 0;
+	}
+
+	return i;
+}
+
+
+extern LZMA_API(lzma_index *)
+lzma_index_init(lzma_allocator *allocator)
+{
+	index_stream *s;
+
+	lzma_index *i = index_init_plain(allocator);
+	if (i == NULL)
+		return NULL;
+
+	s = index_stream_init(0, 0, 1, 0, allocator);
+	if (s == NULL) {
+		lzma_free(i, allocator);
+		return NULL;
+	}
+
+	index_tree_append(&i->streams, &s->node);
+
+	return i;
+}
+
+
+extern LZMA_API(void)
+lzma_index_end(lzma_index *i, lzma_allocator *allocator)
+{
+	// NOTE: If you modify this function, check also the bottom
+	// of lzma_index_cat().
+	if (i != NULL) {
+		index_tree_end(&i->streams, allocator, &index_stream_end);
+		lzma_free(i, allocator);
+	}
+
+	return;
+}
+
+
+extern void
+lzma_index_prealloc(lzma_index *i, lzma_vli records)
+{
+	if (records > PREALLOC_MAX)
+		records = PREALLOC_MAX;
+
+	i->prealloc = (size_t)(records);
+	return;
+}
+
+
+extern LZMA_API(uint64_t)
+lzma_index_memusage(lzma_vli streams, lzma_vli blocks)
+{
+	// This calculates an upper bound that is only a little bit
+	// bigger than the exact maximum memory usage with the given
+	// parameters.
+
+	// Typical malloc() overhead is 2 * sizeof(void *) but we take
+	// a little bit extra just in case. Using LZMA_MEMUSAGE_BASE
+	// instead would give too inaccurate estimate.
+	const size_t alloc_overhead = 4 * sizeof(void *);
+
+	// Amount of memory needed for each Stream base structures.
+	// We assume that every Stream has at least one Block and
+	// thus at least one group.
+	const size_t stream_base = sizeof(index_stream)
+			+ sizeof(index_group) + 2 * alloc_overhead;
+
+	// Amount of memory needed per group.
+	const size_t group_base = sizeof(index_group)
+			+ INDEX_GROUP_SIZE * sizeof(index_record)
+			+ alloc_overhead;
+
+	// Number of groups. There may actually be more, but that overhead
+	// has been taken into account in stream_base already.
+	const lzma_vli groups
+			= (blocks + INDEX_GROUP_SIZE - 1) / INDEX_GROUP_SIZE;
+
+	// Memory used by index_stream and index_group structures.
+	const uint64_t streams_mem = streams * stream_base;
+	const uint64_t groups_mem = groups * group_base;
+
+	// Memory used by the base structure.
+	const uint64_t index_base = sizeof(lzma_index) + alloc_overhead;
+
+	// Validate the arguments and catch integer overflows.
+	// Maximum number of Streams is "only" UINT32_MAX, because
+	// that limit is used by the tree containing the Streams.
+	const uint64_t limit = UINT64_MAX - index_base;
+	if (streams == 0 || streams > UINT32_MAX || blocks > LZMA_VLI_MAX
+			|| streams > limit / stream_base
+			|| groups > limit / group_base
+			|| limit - streams_mem < groups_mem)
+		return UINT64_MAX;
+
+	return index_base + streams_mem + groups_mem;
+}
+
+
+extern LZMA_API(uint64_t)
+lzma_index_memused(const lzma_index *i)
+{
+	return lzma_index_memusage(i->streams.count, i->record_count);
+}
+
+
+extern LZMA_API(lzma_vli)
+lzma_index_block_count(const lzma_index *i)
+{
+	return i->record_count;
+}
+
+
+extern LZMA_API(lzma_vli)
+lzma_index_stream_count(const lzma_index *i)
+{
+	return i->streams.count;
+}
+
+
+extern LZMA_API(lzma_vli)
+lzma_index_size(const lzma_index *i)
+{
+	return index_size(i->record_count, i->index_list_size);
+}
+
+
+extern LZMA_API(lzma_vli)
+lzma_index_total_size(const lzma_index *i)
+{
+	return i->total_size;
+}
+
+
+extern LZMA_API(lzma_vli)
+lzma_index_stream_size(const lzma_index *i)
+{
+	// Stream Header + Blocks + Index + Stream Footer
+	return LZMA_STREAM_HEADER_SIZE + i->total_size
+			+ index_size(i->record_count, i->index_list_size)
+			+ LZMA_STREAM_HEADER_SIZE;
+}
+
+
+static lzma_vli
+index_file_size(lzma_vli compressed_base, lzma_vli unpadded_sum,
+		lzma_vli record_count, lzma_vli index_list_size,
+		lzma_vli stream_padding)
+{
+	// Earlier Streams and Stream Paddings + Stream Header
+	// + Blocks + Index + Stream Footer + Stream Padding
+	//
+	// This might go over LZMA_VLI_MAX due to too big unpadded_sum
+	// when this function is used in lzma_index_append().
+	lzma_vli file_size = compressed_base + 2 * LZMA_STREAM_HEADER_SIZE
+			+ stream_padding + vli_ceil4(unpadded_sum);
+	if (file_size > LZMA_VLI_MAX)
+		return LZMA_VLI_UNKNOWN;
+
+	// The same applies here.
+	file_size += index_size(record_count, index_list_size);
+	if (file_size > LZMA_VLI_MAX)
+		return LZMA_VLI_UNKNOWN;
+
+	return file_size;
+}
+
+
+extern LZMA_API(lzma_vli)
+lzma_index_file_size(const lzma_index *i)
+{
+	const index_stream *s = (const index_stream *)(i->streams.rightmost);
+	const index_group *g = (const index_group *)(s->groups.rightmost);
+	return index_file_size(s->node.compressed_base,
+			g == NULL ? 0 : g->records[g->last].unpadded_sum,
+			s->record_count, s->index_list_size,
+			s->stream_padding);
+}
+
+
+extern LZMA_API(lzma_vli)
+lzma_index_uncompressed_size(const lzma_index *i)
+{
+	return i->uncompressed_size;
+}
+
+
+extern LZMA_API(uint32_t)
+lzma_index_checks(const lzma_index *i)
+{
+	uint32_t checks = i->checks;
+
+	// Get the type of the Check of the last Stream too.
+	const index_stream *s = (const index_stream *)(i->streams.rightmost);
+	if (s->stream_flags.version != UINT32_MAX)
+		checks |= UINT32_C(1) << s->stream_flags.check;
+
+	return checks;
+}
+
+
+extern uint32_t
+lzma_index_padding_size(const lzma_index *i)
+{
+	return (LZMA_VLI_C(4) - index_size_unpadded(
+			i->record_count, i->index_list_size)) & 3;
+}
+
+
+extern LZMA_API(lzma_ret)
+lzma_index_stream_flags(lzma_index *i, const lzma_stream_flags *stream_flags)
+{
+	index_stream *s;
+
+	if (i == NULL || stream_flags == NULL)
+		return LZMA_PROG_ERROR;
+
+	// Validate the Stream Flags.
+	return_if_error(lzma_stream_flags_compare(
+			stream_flags, stream_flags));
+
+	s = (index_stream *)(i->streams.rightmost);
+	s->stream_flags = *stream_flags;
+
+	return LZMA_OK;
+}
+
+
+extern LZMA_API(lzma_ret)
+lzma_index_stream_padding(lzma_index *i, lzma_vli stream_padding)
+{
+	index_stream *s;
+	lzma_vli old_stream_padding;
+
+	if (i == NULL || stream_padding > LZMA_VLI_MAX
+			|| (stream_padding & 3) != 0)
+		return LZMA_PROG_ERROR;
+
+	s = (index_stream *)(i->streams.rightmost);
+
+	// Check that the new value won't make the file grow too big.
+	old_stream_padding = s->stream_padding;
+	s->stream_padding = 0;
+	if (lzma_index_file_size(i) + stream_padding > LZMA_VLI_MAX) {
+		s->stream_padding = old_stream_padding;
+		return LZMA_DATA_ERROR;
+	}
+
+	s->stream_padding = stream_padding;
+	return LZMA_OK;
+}
+
+
+extern LZMA_API(lzma_ret)
+lzma_index_append(lzma_index *i, lzma_allocator *allocator,
+		lzma_vli unpadded_size, lzma_vli uncompressed_size)
+{
+	index_stream *s;
+	index_group *g;
+	lzma_vli compressed_base;
+	lzma_vli uncompressed_base;
+	uint32_t index_list_size_add;
+
+	// Validate.
+	if (i == NULL || unpadded_size < UNPADDED_SIZE_MIN
+			|| unpadded_size > UNPADDED_SIZE_MAX
+			|| uncompressed_size > LZMA_VLI_MAX)
+		return LZMA_PROG_ERROR;
+
+	s = (index_stream *)(i->streams.rightmost);
+	g = (index_group *)(s->groups.rightmost);
+
+	compressed_base = g == NULL ? 0
+			: vli_ceil4(g->records[g->last].unpadded_sum);
+	uncompressed_base = g == NULL ? 0
+			: g->records[g->last].uncompressed_sum;
+	index_list_size_add = lzma_vli_size(unpadded_size)
+			+ lzma_vli_size(uncompressed_size);
+
+	// Check that the file size will stay within limits.
+	if (index_file_size(s->node.compressed_base,
+			compressed_base + unpadded_size, s->record_count + 1,
+			s->index_list_size + index_list_size_add,
+			s->stream_padding) == LZMA_VLI_UNKNOWN)
+		return LZMA_DATA_ERROR;
+
+	// The size of the Index field must not exceed the maximum value
+	// that can be stored in the Backward Size field.
+	if (index_size(i->record_count + 1,
+			i->index_list_size + index_list_size_add)
+			> LZMA_BACKWARD_SIZE_MAX)
+		return LZMA_DATA_ERROR;
+
+	if (g != NULL && g->last + 1 < g->allocated) {
+		// There is space in the last group at least for one Record.
+		++g->last;
+	} else {
+		// We need to allocate a new group.
+		g = lzma_alloc(sizeof(index_group)
+				+ i->prealloc * sizeof(index_record),
+				allocator);
+		if (g == NULL)
+			return LZMA_MEM_ERROR;
+
+		g->last = 0;
+		g->allocated = i->prealloc;
+
+		// Reset prealloc so that if the application happens to
+		// add new Records, the allocation size will be sane.
+		i->prealloc = INDEX_GROUP_SIZE;
+
+		// Set the start offsets of this group.
+		g->node.uncompressed_base = uncompressed_base;
+		g->node.compressed_base = compressed_base;
+		g->number_base = s->record_count + 1;
+
+		// Add the new group to the Stream.
+		index_tree_append(&s->groups, &g->node);
+	}
+
+	// Add the new Record to the group.
+	g->records[g->last].uncompressed_sum
+			= uncompressed_base + uncompressed_size;
+	g->records[g->last].unpadded_sum
+			= compressed_base + unpadded_size;
+
+	// Update the totals.
+	++s->record_count;
+	s->index_list_size += index_list_size_add;
+
+	i->total_size += vli_ceil4(unpadded_size);
+	i->uncompressed_size += uncompressed_size;
+	++i->record_count;
+	i->index_list_size += index_list_size_add;
+
+	return LZMA_OK;
+}
+
+
+/// Structure to pass info to index_cat_helper()
+typedef struct {
+	/// Uncompressed size of the destination
+	lzma_vli uncompressed_size;
+
+	/// Compressed file size of the destination
+	lzma_vli file_size;
+
+	/// Same as above but for Block numbers
+	lzma_vli block_number_add;
+
+	/// Number of Streams that were in the destination index before we
+	/// started appending new Streams from the source index. This is
+	/// used to fix the Stream numbering.
+	uint32_t stream_number_add;
+
+	/// Destination index' Stream tree
+	index_tree *streams;
+
+} index_cat_info;
+
+
+/// Add the Stream nodes from the source index to dest using recursion.
+/// Simplest iterative traversal of the source tree wouldn't work, because
+/// we update the pointers in nodes when moving them to the destination tree.
+static void
+index_cat_helper(const index_cat_info *info, index_stream *this)
+{
+	index_stream *left = (index_stream *)(this->node.left);
+	index_stream *right = (index_stream *)(this->node.right);
+
+	if (left != NULL)
+		index_cat_helper(info, left);
+
+	this->node.uncompressed_base += info->uncompressed_size;
+	this->node.compressed_base += info->file_size;
+	this->number += info->stream_number_add;
+	this->block_number_base += info->block_number_add;
+	index_tree_append(info->streams, &this->node);
+
+	if (right != NULL)
+		index_cat_helper(info, right);
+
+	return;
+}
+
+
+extern LZMA_API(lzma_ret)
+lzma_index_cat(lzma_index *LZMA_RESTRICT dest, lzma_index *LZMA_RESTRICT src,
+		lzma_allocator *allocator)
+{
+	index_cat_info info;
+	const lzma_vli dest_file_size = lzma_index_file_size(dest);
+
+	// Check that we don't exceed the file size limits.
+	if (dest_file_size + lzma_index_file_size(src) > LZMA_VLI_MAX
+			|| dest->uncompressed_size + src->uncompressed_size
+				> LZMA_VLI_MAX)
+		return LZMA_DATA_ERROR;
+
+	// Check that the encoded size of the combined lzma_indexes stays
+	// within limits. In theory, this should be done only if we know
+	// that the user plans to actually combine the Streams and thus
+	// construct a single Index (probably rare). However, exceeding
+	// this limit is quite theoretical, so we do this check always
+	// to simplify things elsewhere.
+	{
+		const lzma_vli dest_size = index_size_unpadded(
+				dest->record_count, dest->index_list_size);
+		const lzma_vli src_size = index_size_unpadded(
+				src->record_count, src->index_list_size);
+		if (vli_ceil4(dest_size + src_size) > LZMA_BACKWARD_SIZE_MAX)
+			return LZMA_DATA_ERROR;
+	}
+
+	// Optimize the last group to minimize memory usage. Allocation has
+	// to be done before modifying dest or src.
+	{
+		index_stream *s = (index_stream *)(dest->streams.rightmost);
+		index_group *g = (index_group *)(s->groups.rightmost);
+		if (g != NULL && g->last + 1 < g->allocated) {
+			index_group *newg;
+
+			assert(g->node.left == NULL);
+			assert(g->node.right == NULL);
+
+			newg = lzma_alloc(sizeof(index_group)
+					+ (g->last + 1)
+					* sizeof(index_record),
+					allocator);
+			if (newg == NULL)
+				return LZMA_MEM_ERROR;
+
+			newg->node = g->node;
+			newg->allocated = g->last + 1;
+			newg->last = g->last;
+			newg->number_base = g->number_base;
+
+			memcpy(newg->records, g->records, newg->allocated
+					* sizeof(index_record));
+
+			if (g->node.parent != NULL) {
+				assert(g->node.parent->right == &g->node);
+				g->node.parent->right = &newg->node;
+			}
+
+			if (s->groups.leftmost == &g->node) {
+				assert(s->groups.root == &g->node);
+				s->groups.leftmost = &newg->node;
+				s->groups.root = &newg->node;
+			}
+
+			if (s->groups.rightmost == &g->node)
+				s->groups.rightmost = &newg->node;
+
+			lzma_free(g, allocator);
+		}
+	}
+
+	// Add all the Streams from src to dest. Update the base offsets
+	// of each Stream from src.
+	info.uncompressed_size = dest->uncompressed_size;
+	info.file_size = dest_file_size;
+	info.stream_number_add = dest->streams.count;
+	info.block_number_add = dest->record_count;
+	info.streams = &dest->streams;
+
+	index_cat_helper(&info, (index_stream *)(src->streams.root));
+
+	// Update info about all the combined Streams.
+	dest->uncompressed_size += src->uncompressed_size;
+	dest->total_size += src->total_size;
+	dest->record_count += src->record_count;
+	dest->index_list_size += src->index_list_size;
+	dest->checks = lzma_index_checks(dest) | src->checks;
+
+	// There's nothing else left in src than the base structure.
+	lzma_free(src, allocator);
+
+	return LZMA_OK;
+}
+
+
+/// Duplicate an index_stream.
+static index_stream *
+index_dup_stream(const index_stream *src, lzma_allocator *allocator)
+{
+	index_stream *dest;
+	index_group *destg;
+	index_group *srcg;
+	size_t i = 0;
+
+	// Catch a somewhat theoretical integer overflow.
+	if (src->record_count > PREALLOC_MAX)
+		return NULL;
+
+	// Allocate and initialize a new Stream.
+	dest = index_stream_init(src->node.compressed_base,
+			src->node.uncompressed_base, src->number,
+			src->block_number_base, allocator);
+
+	// Return immediately if allocation failed or if there are
+	// no groups to duplicate.
+	if (dest == NULL || src->groups.leftmost == NULL)
+		return dest;
+
+	// Copy the overall information.
+	dest->record_count = src->record_count;
+	dest->index_list_size = src->index_list_size;
+	dest->stream_flags = src->stream_flags;
+	dest->stream_padding = src->stream_padding;
+
+	// Allocate memory for the Records. We put all the Records into
+	// a single group. It's simplest and also tends to make
+	// lzma_index_locate() a little bit faster with very big Indexes.
+	destg = lzma_alloc(sizeof(index_group)
+			+ src->record_count * sizeof(index_record),
+			allocator);
+	if (destg == NULL) {
+		index_stream_end(dest, allocator);
+		return NULL;
+	}
+
+	// Initialize destg.
+	destg->node.uncompressed_base = 0;
+	destg->node.compressed_base = 0;
+	destg->number_base = 1;
+	destg->allocated = src->record_count;
+	destg->last = src->record_count - 1;
+
+	// Go through all the groups in src and copy the Records into destg.
+	srcg = (index_group *)(src->groups.leftmost);
+	do {
+		memcpy(destg->records + i, srcg->records,
+				(srcg->last + 1) * sizeof(index_record));
+		i += srcg->last + 1;
+		srcg = index_tree_next(&srcg->node);
+	} while (srcg != NULL);
+
+	assert(i == destg->allocated);
+
+	// Add the group to the new Stream.
+	index_tree_append(&dest->groups, &destg->node);
+
+	return dest;
+}
+
+
+extern LZMA_API(lzma_index *)
+lzma_index_dup(const lzma_index *src, lzma_allocator *allocator)
+{
+	index_stream *srcstream;
+	index_stream *deststream;
+
+	// Allocate the base structure (no initial Stream).
+	lzma_index *dest = index_init_plain(allocator);
+	if (dest == NULL)
+		return NULL;
+
+	// Copy the totals.
+	dest->uncompressed_size = src->uncompressed_size;
+	dest->total_size = src->total_size;
+	dest->record_count = src->record_count;
+	dest->index_list_size = src->index_list_size;
+
+	// Copy the Streams and the groups in them.
+	srcstream = (index_stream *)(src->streams.leftmost);
+	do {
+		deststream = index_dup_stream(srcstream, allocator);
+		if (deststream == NULL) {
+			lzma_index_end(dest, allocator);
+			return NULL;
+		}
+
+		index_tree_append(&dest->streams, &deststream->node);
+
+		srcstream = index_tree_next(&srcstream->node);
+	} while (srcstream != NULL);
+
+	return dest;
+}
+
+
+/// Indexing for lzma_index_iter.internal[]
+enum {
+	ITER_INDEX,
+	ITER_STREAM,
+	ITER_GROUP,
+	ITER_RECORD,
+	ITER_METHOD,
+};
+
+
+/// Values for lzma_index_iter.internal[ITER_METHOD].s
+enum {
+	ITER_METHOD_NORMAL,
+	ITER_METHOD_NEXT,
+	ITER_METHOD_LEFTMOST,
+};
+
+
+static void
+iter_set_info(lzma_index_iter *iter)
+{
+	const lzma_index *i = iter->internal[ITER_INDEX].p;
+	const index_stream *stream = iter->internal[ITER_STREAM].p;
+	const index_group *group = iter->internal[ITER_GROUP].p;
+	const size_t record = iter->internal[ITER_RECORD].s;
+
+	// lzma_index_iter.internal must not contain a pointer to the last
+	// group in the index, because that may be reallocated by
+	// lzma_index_cat().
+	if (group == NULL) {
+		// There are no groups.
+		assert(stream->groups.root == NULL);
+		iter->internal[ITER_METHOD].s = ITER_METHOD_LEFTMOST;
+
+	} else if (i->streams.rightmost != &stream->node
+			|| stream->groups.rightmost != &group->node) {
+		// The group is not not the last group in the index.
+		iter->internal[ITER_METHOD].s = ITER_METHOD_NORMAL;
+
+	} else if (stream->groups.leftmost != &group->node) {
+		// The group isn't the only group in the Stream, thus we
+		// know that it must have a parent group i.e. it's not
+		// the root node.
+		assert(stream->groups.root != &group->node);
+		assert(group->node.parent->right == &group->node);
+		iter->internal[ITER_METHOD].s = ITER_METHOD_NEXT;
+		iter->internal[ITER_GROUP].p = group->node.parent;
+
+	} else {
+		// The Stream has only one group.
+		assert(stream->groups.root == &group->node);
+		assert(group->node.parent == NULL);
+		iter->internal[ITER_METHOD].s = ITER_METHOD_LEFTMOST;
+		iter->internal[ITER_GROUP].p = NULL;
+	}
+
+	iter->stream.number = stream->number;
+	iter->stream.block_count = stream->record_count;
+	iter->stream.compressed_offset = stream->node.compressed_base;
+	iter->stream.uncompressed_offset = stream->node.uncompressed_base;
+
+	// iter->stream.flags will be NULL if the Stream Flags haven't been
+	// set with lzma_index_stream_flags().
+	iter->stream.flags = stream->stream_flags.version == UINT32_MAX
+			? NULL : &stream->stream_flags;
+	iter->stream.padding = stream->stream_padding;
+
+	if (stream->groups.rightmost == NULL) {
+		// Stream has no Blocks.
+		iter->stream.compressed_size = index_size(0, 0)
+				+ 2 * LZMA_STREAM_HEADER_SIZE;
+		iter->stream.uncompressed_size = 0;
+	} else {
+		const index_group *g = (const index_group *)(
+				stream->groups.rightmost);
+
+		// Stream Header + Stream Footer + Index + Blocks
+		iter->stream.compressed_size = 2 * LZMA_STREAM_HEADER_SIZE
+				+ index_size(stream->record_count,
+					stream->index_list_size)
+				+ vli_ceil4(g->records[g->last].unpadded_sum);
+		iter->stream.uncompressed_size
+				= g->records[g->last].uncompressed_sum;
+	}
+
+	if (group != NULL) {
+		iter->block.number_in_stream = group->number_base + record;
+		iter->block.number_in_file = iter->block.number_in_stream
+				+ stream->block_number_base;
+
+		iter->block.compressed_stream_offset
+				= record == 0 ? group->node.compressed_base
+				: vli_ceil4(group->records[
+					record - 1].unpadded_sum);
+		iter->block.uncompressed_stream_offset
+				= record == 0 ? group->node.uncompressed_base
+				: group->records[record - 1].uncompressed_sum;
+
+		iter->block.uncompressed_size
+				= group->records[record].uncompressed_sum
+				- iter->block.uncompressed_stream_offset;
+		iter->block.unpadded_size
+				= group->records[record].unpadded_sum
+				- iter->block.compressed_stream_offset;
+		iter->block.total_size = vli_ceil4(iter->block.unpadded_size);
+
+		iter->block.compressed_stream_offset
+				+= LZMA_STREAM_HEADER_SIZE;
+
+		iter->block.compressed_file_offset
+				= iter->block.compressed_stream_offset
+				+ iter->stream.compressed_offset;
+		iter->block.uncompressed_file_offset
+				= iter->block.uncompressed_stream_offset
+				+ iter->stream.uncompressed_offset;
+	}
+
+	return;
+}
+
+
+extern LZMA_API(void)
+lzma_index_iter_init(lzma_index_iter *iter, const lzma_index *i)
+{
+	iter->internal[ITER_INDEX].p = i;
+	lzma_index_iter_rewind(iter);
+	return;
+}
+
+
+extern LZMA_API(void)
+lzma_index_iter_rewind(lzma_index_iter *iter)
+{
+	iter->internal[ITER_STREAM].p = NULL;
+	iter->internal[ITER_GROUP].p = NULL;
+	iter->internal[ITER_RECORD].s = 0;
+	iter->internal[ITER_METHOD].s = ITER_METHOD_NORMAL;
+	return;
+}
+
+
+extern LZMA_API(lzma_bool)
+lzma_index_iter_next(lzma_index_iter *iter, lzma_index_iter_mode mode)
+{
+	const lzma_index *i;
+	const index_stream *stream;
+	const index_group *group;
+	size_t record;
+
+	// Catch unsupported mode values.
+	if ((unsigned int)(mode) > LZMA_INDEX_ITER_NONEMPTY_BLOCK)
+		return true;
+
+	i = iter->internal[ITER_INDEX].p;
+	stream = iter->internal[ITER_STREAM].p;
+	group = NULL;
+	record = iter->internal[ITER_RECORD].s;
+
+	// If we are being asked for the next Stream, leave group to NULL
+	// so that the rest of the this function thinks that this Stream
+	// has no groups and will thus go to the next Stream.
+	if (mode != LZMA_INDEX_ITER_STREAM) {
+		// Get the pointer to the current group. See iter_set_inf()
+		// for explanation.
+		switch (iter->internal[ITER_METHOD].s) {
+		case ITER_METHOD_NORMAL:
+			group = iter->internal[ITER_GROUP].p;
+			break;
+
+		case ITER_METHOD_NEXT:
+			group = index_tree_next(iter->internal[ITER_GROUP].p);
+			break;
+
+		case ITER_METHOD_LEFTMOST:
+			group = (const index_group *)(
+					stream->groups.leftmost);
+			break;
+		}
+	}
+
+again:
+	if (stream == NULL) {
+		// We at the beginning of the lzma_index.
+		// Locate the first Stream.
+		stream = (const index_stream *)(i->streams.leftmost);
+		if (mode >= LZMA_INDEX_ITER_BLOCK) {
+			// Since we are being asked to return information
+			// about the first a Block, skip Streams that have
+			// no Blocks.
+			while (stream->groups.leftmost == NULL) {
+				stream = index_tree_next(&stream->node);
+				if (stream == NULL)
+					return true;
+			}
+		}
+
+		// Start from the first Record in the Stream.
+		group = (const index_group *)(stream->groups.leftmost);
+		record = 0;
+
+	} else if (group != NULL && record < group->last) {
+		// The next Record is in the same group.
+		++record;
+
+	} else {
+		// This group has no more Records or this Stream has
+		// no Blocks at all.
+		record = 0;
+
+		// If group is not NULL, this Stream has at least one Block
+		// and thus at least one group. Find the next group.
+		if (group != NULL)
+			group = index_tree_next(&group->node);
+
+		if (group == NULL) {
+			// This Stream has no more Records. Find the next
+			// Stream. If we are being asked to return information
+			// about a Block, we skip empty Streams.
+			do {
+				stream = index_tree_next(&stream->node);
+				if (stream == NULL)
+					return true;
+			} while (mode >= LZMA_INDEX_ITER_BLOCK
+					&& stream->groups.leftmost == NULL);
+
+			group = (const index_group *)(
+					stream->groups.leftmost);
+		}
+	}
+
+	if (mode == LZMA_INDEX_ITER_NONEMPTY_BLOCK) {
+		// We need to look for the next Block again if this Block
+		// is empty.
+		if (record == 0) {
+			if (group->node.uncompressed_base
+					== group->records[0].uncompressed_sum)
+				goto again;
+		} else if (group->records[record - 1].uncompressed_sum
+				== group->records[record].uncompressed_sum) {
+			goto again;
+		}
+	}
+
+	iter->internal[ITER_STREAM].p = stream;
+	iter->internal[ITER_GROUP].p = group;
+	iter->internal[ITER_RECORD].s = record;
+
+	iter_set_info(iter);
+
+	return false;
+}
+
+
+extern LZMA_API(lzma_bool)
+lzma_index_iter_locate(lzma_index_iter *iter, lzma_vli target)
+{
+	const index_stream *stream;
+	const index_group *group;
+	size_t left, right;
+
+	const lzma_index *i = iter->internal[ITER_INDEX].p;
+
+	// If the target is past the end of the file, return immediately.
+	if (i->uncompressed_size <= target)
+		return true;
+
+	// Locate the Stream containing the target offset.
+	stream = index_tree_locate(&i->streams, target);
+	assert(stream != NULL);
+	target -= stream->node.uncompressed_base;
+
+	// Locate the group containing the target offset.
+	group = index_tree_locate(&stream->groups, target);
+	assert(group != NULL);
+
+	// Use binary search to locate the exact Record. It is the first
+	// Record whose uncompressed_sum is greater than target.
+	// This is because we want the rightmost Record that fullfills the
+	// search criterion. It is possible that there are empty Blocks;
+	// we don't want to return them.
+	left = 0;
+	right = group->last;
+
+	while (left < right) {
+		const size_t pos = left + (right - left) / 2;
+		if (group->records[pos].uncompressed_sum <= target)
+			left = pos + 1;
+		else
+			right = pos;
+	}
+
+	iter->internal[ITER_STREAM].p = stream;
+	iter->internal[ITER_GROUP].p = group;
+	iter->internal[ITER_RECORD].s = left;
+
+	iter_set_info(iter);
+
+	return false;
+}
diff --git a/Utilities/cmliblzma/liblzma/common/index.h b/Utilities/cmliblzma/liblzma/common/index.h
new file mode 100644
index 0000000..64e9724
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/index.h
@@ -0,0 +1,73 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       index.h
+/// \brief      Handling of Index
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#ifndef LZMA_INDEX_H
+#define LZMA_INDEX_H
+
+#include "common.h"
+
+
+/// Minimum Unpadded Size
+#define UNPADDED_SIZE_MIN LZMA_VLI_C(5)
+
+/// Maximum Unpadded Size
+#define UNPADDED_SIZE_MAX (LZMA_VLI_MAX & ~LZMA_VLI_C(3))
+
+
+/// Get the size of the Index Padding field. This is needed by Index encoder
+/// and decoder, but applications should have no use for this.
+extern uint32_t lzma_index_padding_size(const lzma_index *i);
+
+
+/// Set for how many Records to allocate memory the next time
+/// lzma_index_append() needs to allocate space for a new Record.
+/// This is used only by the Index decoder.
+extern void lzma_index_prealloc(lzma_index *i, lzma_vli records);
+
+
+/// Round the variable-length integer to the next multiple of four.
+static inline lzma_vli
+vli_ceil4(lzma_vli vli)
+{
+	assert(vli <= LZMA_VLI_MAX);
+	return (vli + 3) & ~LZMA_VLI_C(3);
+}
+
+
+/// Calculate the size of the Index field excluding Index Padding
+static inline lzma_vli
+index_size_unpadded(lzma_vli count, lzma_vli index_list_size)
+{
+	// Index Indicator + Number of Records + List of Records + CRC32
+	return 1 + lzma_vli_size(count) + index_list_size + 4;
+}
+
+
+/// Calculate the size of the Index field including Index Padding
+static inline lzma_vli
+index_size(lzma_vli count, lzma_vli index_list_size)
+{
+	return vli_ceil4(index_size_unpadded(count, index_list_size));
+}
+
+
+/// Calculate the total size of the Stream
+static inline lzma_vli
+index_stream_size(lzma_vli blocks_size,
+		lzma_vli count, lzma_vli index_list_size)
+{
+	return LZMA_STREAM_HEADER_SIZE + blocks_size
+			+ index_size(count, index_list_size)
+			+ LZMA_STREAM_HEADER_SIZE;
+}
+
+#endif
diff --git a/Utilities/cmliblzma/liblzma/common/index_decoder.c b/Utilities/cmliblzma/liblzma/common/index_decoder.c
new file mode 100644
index 0000000..943cfd5
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/index_decoder.c
@@ -0,0 +1,347 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       index_decoder.c
+/// \brief      Decodes the Index field
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "index.h"
+#include "check.h"
+
+
+struct lzma_coder_s {
+	enum {
+		SEQ_INDICATOR,
+		SEQ_COUNT,
+		SEQ_MEMUSAGE,
+		SEQ_UNPADDED,
+		SEQ_UNCOMPRESSED,
+		SEQ_PADDING_INIT,
+		SEQ_PADDING,
+		SEQ_CRC32,
+	} sequence;
+
+	/// Memory usage limit
+	uint64_t memlimit;
+
+	/// Target Index
+	lzma_index *index;
+
+	/// Pointer give by the application, which is set after
+	/// successful decoding.
+	lzma_index **index_ptr;
+
+	/// Number of Records left to decode.
+	lzma_vli count;
+
+	/// The most recent Unpadded Size field
+	lzma_vli unpadded_size;
+
+	/// The most recent Uncompressed Size field
+	lzma_vli uncompressed_size;
+
+	/// Position in integers
+	size_t pos;
+
+	/// CRC32 of the List of Records field
+	uint32_t crc32;
+};
+
+
+static lzma_ret
+index_decode(lzma_coder *coder, lzma_allocator *allocator,
+		const uint8_t *LZMA_RESTRICT in, size_t *LZMA_RESTRICT in_pos,
+		size_t in_size,
+		uint8_t *LZMA_RESTRICT out lzma_attribute((__unused__)),
+		size_t *LZMA_RESTRICT out_pos lzma_attribute((__unused__)),
+		size_t out_size lzma_attribute((__unused__)),
+		lzma_action action lzma_attribute((__unused__)))
+{
+	// Similar optimization as in index_encoder.c
+	const size_t in_start = *in_pos;
+	lzma_ret ret = LZMA_OK;
+
+	while (*in_pos < in_size)
+	switch (coder->sequence) {
+	case SEQ_INDICATOR:
+		// Return LZMA_DATA_ERROR instead of e.g. LZMA_PROG_ERROR or
+		// LZMA_FORMAT_ERROR, because a typical usage case for Index
+		// decoder is when parsing the Stream backwards. If seeking
+		// backward from the Stream Footer gives us something that
+		// doesn't begin with Index Indicator, the file is considered
+		// corrupt, not "programming error" or "unrecognized file
+		// format". One could argue that the application should
+		// verify the Index Indicator before trying to decode the
+		// Index, but well, I suppose it is simpler this way.
+		if (in[(*in_pos)++] != 0x00)
+			return LZMA_DATA_ERROR;
+
+		coder->sequence = SEQ_COUNT;
+		break;
+
+	case SEQ_COUNT:
+		ret = lzma_vli_decode(&coder->count, &coder->pos,
+				in, in_pos, in_size);
+		if (ret != LZMA_STREAM_END)
+			goto out;
+
+		coder->pos = 0;
+		coder->sequence = SEQ_MEMUSAGE;
+
+	// Fall through
+
+	case SEQ_MEMUSAGE:
+		if (lzma_index_memusage(1, coder->count) > coder->memlimit) {
+			ret = LZMA_MEMLIMIT_ERROR;
+			goto out;
+		}
+
+		// Tell the Index handling code how many Records this
+		// Index has to allow it to allocate memory more efficiently.
+		lzma_index_prealloc(coder->index, coder->count);
+
+		ret = LZMA_OK;
+		coder->sequence = coder->count == 0
+				? SEQ_PADDING_INIT : SEQ_UNPADDED;
+		break;
+
+	case SEQ_UNPADDED:
+	case SEQ_UNCOMPRESSED: {
+		lzma_vli *size = coder->sequence == SEQ_UNPADDED
+				? &coder->unpadded_size
+				: &coder->uncompressed_size;
+
+		ret = lzma_vli_decode(size, &coder->pos,
+				in, in_pos, in_size);
+		if (ret != LZMA_STREAM_END)
+			goto out;
+
+		ret = LZMA_OK;
+		coder->pos = 0;
+
+		if (coder->sequence == SEQ_UNPADDED) {
+			// Validate that encoded Unpadded Size isn't too small
+			// or too big.
+			if (coder->unpadded_size < UNPADDED_SIZE_MIN
+					|| coder->unpadded_size
+						> UNPADDED_SIZE_MAX)
+				return LZMA_DATA_ERROR;
+
+			coder->sequence = SEQ_UNCOMPRESSED;
+		} else {
+			// Add the decoded Record to the Index.
+			return_if_error(lzma_index_append(
+					coder->index, allocator,
+					coder->unpadded_size,
+					coder->uncompressed_size));
+
+			// Check if this was the last Record.
+			coder->sequence = --coder->count == 0
+					? SEQ_PADDING_INIT
+					: SEQ_UNPADDED;
+		}
+
+		break;
+	}
+
+	case SEQ_PADDING_INIT:
+		coder->pos = lzma_index_padding_size(coder->index);
+		coder->sequence = SEQ_PADDING;
+
+	// Fall through
+
+	case SEQ_PADDING:
+		if (coder->pos > 0) {
+			--coder->pos;
+			if (in[(*in_pos)++] != 0x00)
+				return LZMA_DATA_ERROR;
+
+			break;
+		}
+
+		// Finish the CRC32 calculation.
+		coder->crc32 = lzma_crc32(in + in_start,
+				*in_pos - in_start, coder->crc32);
+
+		coder->sequence = SEQ_CRC32;
+
+	// Fall through
+
+	case SEQ_CRC32:
+		do {
+			if (*in_pos == in_size)
+				return LZMA_OK;
+
+			if (((coder->crc32 >> (coder->pos * 8)) & 0xFF)
+					!= in[(*in_pos)++])
+				return LZMA_DATA_ERROR;
+
+		} while (++coder->pos < 4);
+
+		// Decoding was successful, now we can let the application
+		// see the decoded Index.
+		*coder->index_ptr = coder->index;
+
+		// Make index NULL so we don't free it unintentionally.
+		coder->index = NULL;
+
+		return LZMA_STREAM_END;
+
+	default:
+		assert(0);
+		return LZMA_PROG_ERROR;
+	}
+
+out:
+	// Update the CRC32,
+	coder->crc32 = lzma_crc32(in + in_start,
+			*in_pos - in_start, coder->crc32);
+
+	return ret;
+}
+
+
+static void
+index_decoder_end(lzma_coder *coder, lzma_allocator *allocator)
+{
+	lzma_index_end(coder->index, allocator);
+	lzma_free(coder, allocator);
+	return;
+}
+
+
+static lzma_ret
+index_decoder_memconfig(lzma_coder *coder, uint64_t *memusage,
+		uint64_t *old_memlimit, uint64_t new_memlimit)
+{
+	*memusage = lzma_index_memusage(1, coder->count);
+	*old_memlimit = coder->memlimit;
+
+	if (new_memlimit != 0) {
+		if (new_memlimit < *memusage)
+			return LZMA_MEMLIMIT_ERROR;
+
+		coder->memlimit = new_memlimit;
+	}
+
+	return LZMA_OK;
+}
+
+
+static lzma_ret
+index_decoder_reset(lzma_coder *coder, lzma_allocator *allocator,
+		lzma_index **i, uint64_t memlimit)
+{
+	// Remember the pointer given by the application. We will set it
+	// to point to the decoded Index only if decoding is successful.
+	// Before that, keep it NULL so that applications can always safely
+	// pass it to lzma_index_end() no matter did decoding succeed or not.
+	coder->index_ptr = i;
+	*i = NULL;
+
+	// We always allocate a new lzma_index.
+	coder->index = lzma_index_init(allocator);
+	if (coder->index == NULL)
+		return LZMA_MEM_ERROR;
+
+	// Initialize the rest.
+	coder->sequence = SEQ_INDICATOR;
+	coder->memlimit = memlimit;
+	coder->count = 0; // Needs to be initialized due to _memconfig().
+	coder->pos = 0;
+	coder->crc32 = 0;
+
+	return LZMA_OK;
+}
+
+
+static lzma_ret
+index_decoder_init(lzma_next_coder *next, lzma_allocator *allocator,
+		lzma_index **i, uint64_t memlimit)
+{
+	lzma_next_coder_init(&index_decoder_init, next, allocator);
+
+	if (i == NULL || memlimit == 0)
+		return LZMA_PROG_ERROR;
+
+	if (next->coder == NULL) {
+		next->coder = lzma_alloc(sizeof(lzma_coder), allocator);
+		if (next->coder == NULL)
+			return LZMA_MEM_ERROR;
+
+		next->code = &index_decode;
+		next->end = &index_decoder_end;
+		next->memconfig = &index_decoder_memconfig;
+		next->coder->index = NULL;
+	} else {
+		lzma_index_end(next->coder->index, allocator);
+	}
+
+	return index_decoder_reset(next->coder, allocator, i, memlimit);
+}
+
+
+extern LZMA_API(lzma_ret)
+lzma_index_decoder(lzma_stream *strm, lzma_index **i, uint64_t memlimit)
+{
+	lzma_next_strm_init2(index_decoder_init, strm, i, memlimit);
+
+	strm->internal->supported_actions[LZMA_RUN] = true;
+	strm->internal->supported_actions[LZMA_FINISH] = true;
+
+	return LZMA_OK;
+}
+
+
+extern LZMA_API(lzma_ret)
+lzma_index_buffer_decode(
+		lzma_index **i, uint64_t *memlimit, lzma_allocator *allocator,
+		const uint8_t *in, size_t *in_pos, size_t in_size)
+{
+	lzma_coder coder;
+	lzma_ret ret;
+
+	// Store the input start position so that we can restore it in case
+	// of an error.
+	const size_t in_start = *in_pos;
+
+	// Sanity checks
+	if (i == NULL || memlimit == NULL
+			|| in == NULL || in_pos == NULL || *in_pos > in_size)
+		return LZMA_PROG_ERROR;
+
+	// Initialize the decoder.
+	return_if_error(index_decoder_reset(&coder, allocator, i, *memlimit));
+
+	// Do the actual decoding.
+	ret = index_decode(&coder, allocator, in, in_pos, in_size,
+			NULL, NULL, 0, LZMA_RUN);
+
+	if (ret == LZMA_STREAM_END) {
+		ret = LZMA_OK;
+	} else {
+		// Something went wrong, free the Index structure and restore
+		// the input position.
+		lzma_index_end(coder.index, allocator);
+		*in_pos = in_start;
+
+		if (ret == LZMA_OK) {
+			// The input is truncated or otherwise corrupt.
+			// Use LZMA_DATA_ERROR instead of LZMA_BUF_ERROR
+			// like lzma_vli_decode() does in single-call mode.
+			ret = LZMA_DATA_ERROR;
+
+		} else if (ret == LZMA_MEMLIMIT_ERROR) {
+			// Tell the caller how much memory would have
+			// been needed.
+			*memlimit = lzma_index_memusage(1, coder.count);
+		}
+	}
+
+	return ret;
+}
diff --git a/Utilities/cmliblzma/liblzma/common/index_encoder.c b/Utilities/cmliblzma/liblzma/common/index_encoder.c
new file mode 100644
index 0000000..194bf21
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/index_encoder.c
@@ -0,0 +1,257 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       index_encoder.c
+/// \brief      Encodes the Index field
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "index_encoder.h"
+#include "index.h"
+#include "check.h"
+
+
+struct lzma_coder_s {
+	enum {
+		SEQ_INDICATOR,
+		SEQ_COUNT,
+		SEQ_UNPADDED,
+		SEQ_UNCOMPRESSED,
+		SEQ_NEXT,
+		SEQ_PADDING,
+		SEQ_CRC32,
+	} sequence;
+
+	/// Index being encoded
+	const lzma_index *index;
+
+	/// Iterator for the Index being encoded
+	lzma_index_iter iter;
+
+	/// Position in integers
+	size_t pos;
+
+	/// CRC32 of the List of Records field
+	uint32_t crc32;
+};
+
+
+static lzma_ret
+index_encode(lzma_coder *coder,
+		lzma_allocator *allocator lzma_attribute((__unused__)),
+		const uint8_t *LZMA_RESTRICT in lzma_attribute((__unused__)),
+		size_t *LZMA_RESTRICT in_pos lzma_attribute((__unused__)),
+		size_t in_size lzma_attribute((__unused__)),
+		uint8_t *LZMA_RESTRICT out, size_t *LZMA_RESTRICT out_pos,
+		size_t out_size,
+		lzma_action action lzma_attribute((__unused__)))
+{
+	// Position where to start calculating CRC32. The idea is that we
+	// need to call lzma_crc32() only once per call to index_encode().
+	const size_t out_start = *out_pos;
+
+	// Return value to use if we return at the end of this function.
+	// We use "goto out" to jump out of the while-switch construct
+	// instead of returning directly, because that way we don't need
+	// to copypaste the lzma_crc32() call to many places.
+	lzma_ret ret = LZMA_OK;
+
+	while (*out_pos < out_size)
+	switch (coder->sequence) {
+	case SEQ_INDICATOR:
+		out[*out_pos] = 0x00;
+		++*out_pos;
+		coder->sequence = SEQ_COUNT;
+		break;
+
+	case SEQ_COUNT: {
+		const lzma_vli count = lzma_index_block_count(coder->index);
+		ret = lzma_vli_encode(count, &coder->pos,
+				out, out_pos, out_size);
+		if (ret != LZMA_STREAM_END)
+			goto out;
+
+		ret = LZMA_OK;
+		coder->pos = 0;
+		coder->sequence = SEQ_NEXT;
+		break;
+	}
+
+	case SEQ_NEXT:
+		if (lzma_index_iter_next(
+				&coder->iter, LZMA_INDEX_ITER_BLOCK)) {
+			// Get the size of the Index Padding field.
+			coder->pos = lzma_index_padding_size(coder->index);
+			assert(coder->pos <= 3);
+			coder->sequence = SEQ_PADDING;
+			break;
+		}
+
+		coder->sequence = SEQ_UNPADDED;
+
+	// Fall through
+
+	case SEQ_UNPADDED:
+	case SEQ_UNCOMPRESSED: {
+		const lzma_vli size = coder->sequence == SEQ_UNPADDED
+				? coder->iter.block.unpadded_size
+				: coder->iter.block.uncompressed_size;
+
+		ret = lzma_vli_encode(size, &coder->pos,
+				out, out_pos, out_size);
+		if (ret != LZMA_STREAM_END)
+			goto out;
+
+		ret = LZMA_OK;
+		coder->pos = 0;
+
+		// Advance to SEQ_UNCOMPRESSED or SEQ_NEXT.
+		++coder->sequence;
+		break;
+	}
+
+	case SEQ_PADDING:
+		if (coder->pos > 0) {
+			--coder->pos;
+			out[(*out_pos)++] = 0x00;
+			break;
+		}
+
+		// Finish the CRC32 calculation.
+		coder->crc32 = lzma_crc32(out + out_start,
+				*out_pos - out_start, coder->crc32);
+
+		coder->sequence = SEQ_CRC32;
+
+	// Fall through
+
+	case SEQ_CRC32:
+		// We don't use the main loop, because we don't want
+		// coder->crc32 to be touched anymore.
+		do {
+			if (*out_pos == out_size)
+				return LZMA_OK;
+
+			out[*out_pos] = (coder->crc32 >> (coder->pos * 8))
+					& 0xFF;
+			++*out_pos;
+
+		} while (++coder->pos < 4);
+
+		return LZMA_STREAM_END;
+
+	default:
+		assert(0);
+		return LZMA_PROG_ERROR;
+	}
+
+out:
+	// Update the CRC32.
+	coder->crc32 = lzma_crc32(out + out_start,
+			*out_pos - out_start, coder->crc32);
+
+	return ret;
+}
+
+
+static void
+index_encoder_end(lzma_coder *coder, lzma_allocator *allocator)
+{
+	lzma_free(coder, allocator);
+	return;
+}
+
+
+static void
+index_encoder_reset(lzma_coder *coder, const lzma_index *i)
+{
+	lzma_index_iter_init(&coder->iter, i);
+
+	coder->sequence = SEQ_INDICATOR;
+	coder->index = i;
+	coder->pos = 0;
+	coder->crc32 = 0;
+
+	return;
+}
+
+
+extern lzma_ret
+lzma_index_encoder_init(lzma_next_coder *next, lzma_allocator *allocator,
+		const lzma_index *i)
+{
+	lzma_next_coder_init(&lzma_index_encoder_init, next, allocator);
+
+	if (i == NULL)
+		return LZMA_PROG_ERROR;
+
+	if (next->coder == NULL) {
+		next->coder = lzma_alloc(sizeof(lzma_coder), allocator);
+		if (next->coder == NULL)
+			return LZMA_MEM_ERROR;
+
+		next->code = &index_encode;
+		next->end = &index_encoder_end;
+	}
+
+	index_encoder_reset(next->coder, i);
+
+	return LZMA_OK;
+}
+
+
+extern LZMA_API(lzma_ret)
+lzma_index_encoder(lzma_stream *strm, const lzma_index *i)
+{
+	lzma_next_strm_init1(lzma_index_encoder_init, strm, i);
+
+	strm->internal->supported_actions[LZMA_RUN] = true;
+	strm->internal->supported_actions[LZMA_FINISH] = true;
+
+	return LZMA_OK;
+}
+
+
+extern LZMA_API(lzma_ret)
+lzma_index_buffer_encode(const lzma_index *i,
+		uint8_t *out, size_t *out_pos, size_t out_size)
+{
+	lzma_coder coder;
+	size_t out_start;
+	lzma_ret ret;
+
+	// Validate the arguments.
+	if (i == NULL || out == NULL || out_pos == NULL || *out_pos > out_size)
+		return LZMA_PROG_ERROR;
+
+	// Don't try to encode if there's not enough output space.
+	if (out_size - *out_pos < lzma_index_size(i))
+		return LZMA_BUF_ERROR;
+
+	// The Index encoder needs just one small data structure so we can
+	// allocate it on stack.
+	index_encoder_reset(&coder, i);
+
+	// Do the actual encoding. This should never fail, but store
+	// the original *out_pos just in case.
+	out_start = *out_pos;
+	ret = index_encode(&coder, NULL, NULL, NULL, 0,
+			out, out_pos, out_size, LZMA_RUN);
+
+	if (ret == LZMA_STREAM_END) {
+		ret = LZMA_OK;
+	} else {
+		// We should never get here, but just in case, restore the
+		// output position and set the error accordingly if something
+		// goes wrong and debugging isn't enabled.
+		assert(0);
+		*out_pos = out_start;
+		ret = LZMA_PROG_ERROR;
+	}
+
+	return ret;
+}
diff --git a/Utilities/cmliblzma/liblzma/common/index_encoder.h b/Utilities/cmliblzma/liblzma/common/index_encoder.h
new file mode 100644
index 0000000..a13c94d
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/index_encoder.h
@@ -0,0 +1,23 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       index_encoder.h
+/// \brief      Encodes the Index field
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#ifndef LZMA_INDEX_ENCODER_H
+#define LZMA_INDEX_ENCODER_H
+
+#include "common.h"
+
+
+extern lzma_ret lzma_index_encoder_init(lzma_next_coder *next,
+		lzma_allocator *allocator, const lzma_index *i);
+
+
+#endif
diff --git a/Utilities/cmliblzma/liblzma/common/index_hash.c b/Utilities/cmliblzma/liblzma/common/index_hash.c
new file mode 100644
index 0000000..0cf86b3
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/index_hash.c
@@ -0,0 +1,336 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       index_hash.c
+/// \brief      Validates Index by using a hash function
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "common.h"
+#include "index.h"
+#include "check.h"
+
+
+typedef struct {
+	/// Sum of the Block sizes (including Block Padding)
+	lzma_vli blocks_size;
+
+	/// Sum of the Uncompressed Size fields
+	lzma_vli uncompressed_size;
+
+	/// Number of Records
+	lzma_vli count;
+
+	/// Size of the List of Index Records as bytes
+	lzma_vli index_list_size;
+
+	/// Check calculated from Unpadded Sizes and Uncompressed Sizes.
+	lzma_check_state check;
+
+} lzma_index_hash_info;
+
+
+struct lzma_index_hash_s {
+	enum {
+		SEQ_BLOCK,
+		SEQ_COUNT,
+		SEQ_UNPADDED,
+		SEQ_UNCOMPRESSED,
+		SEQ_PADDING_INIT,
+		SEQ_PADDING,
+		SEQ_CRC32,
+	} sequence;
+
+	/// Information collected while decoding the actual Blocks.
+	lzma_index_hash_info blocks;
+
+	/// Information collected from the Index field.
+	lzma_index_hash_info records;
+
+	/// Number of Records not fully decoded
+	lzma_vli remaining;
+
+	/// Unpadded Size currently being read from an Index Record.
+	lzma_vli unpadded_size;
+
+	/// Uncompressed Size currently being read from an Index Record.
+	lzma_vli uncompressed_size;
+
+	/// Position in variable-length integers when decoding them from
+	/// the List of Records.
+	size_t pos;
+
+	/// CRC32 of the Index
+	uint32_t crc32;
+};
+
+
+extern LZMA_API(lzma_index_hash *)
+lzma_index_hash_init(lzma_index_hash *index_hash, lzma_allocator *allocator)
+{
+	if (index_hash == NULL) {
+		index_hash = lzma_alloc(sizeof(lzma_index_hash), allocator);
+		if (index_hash == NULL)
+			return NULL;
+	}
+
+	index_hash->sequence = SEQ_BLOCK;
+	index_hash->blocks.blocks_size = 0;
+	index_hash->blocks.uncompressed_size = 0;
+	index_hash->blocks.count = 0;
+	index_hash->blocks.index_list_size = 0;
+	index_hash->records.blocks_size = 0;
+	index_hash->records.uncompressed_size = 0;
+	index_hash->records.count = 0;
+	index_hash->records.index_list_size = 0;
+	index_hash->unpadded_size = 0;
+	index_hash->uncompressed_size = 0;
+	index_hash->pos = 0;
+	index_hash->crc32 = 0;
+
+	// These cannot fail because LZMA_CHECK_BEST is known to be supported.
+	(void)lzma_check_init(&index_hash->blocks.check, LZMA_CHECK_BEST);
+	(void)lzma_check_init(&index_hash->records.check, LZMA_CHECK_BEST);
+
+	return index_hash;
+}
+
+
+extern LZMA_API(void)
+lzma_index_hash_end(lzma_index_hash *index_hash, lzma_allocator *allocator)
+{
+	lzma_free(index_hash, allocator);
+	return;
+}
+
+
+extern LZMA_API(lzma_vli)
+lzma_index_hash_size(const lzma_index_hash *index_hash)
+{
+	// Get the size of the Index from ->blocks instead of ->records for
+	// cases where application wants to know the Index Size before
+	// decoding the Index.
+	return index_size(index_hash->blocks.count,
+			index_hash->blocks.index_list_size);
+}
+
+
+/// Updates the sizes and the hash without any validation.
+static lzma_ret
+hash_append(lzma_index_hash_info *info, lzma_vli unpadded_size,
+		lzma_vli uncompressed_size)
+{
+	const lzma_vli sizes[2] = { unpadded_size, uncompressed_size };
+
+	info->blocks_size += vli_ceil4(unpadded_size);
+	info->uncompressed_size += uncompressed_size;
+	info->index_list_size += lzma_vli_size(unpadded_size)
+			+ lzma_vli_size(uncompressed_size);
+	++info->count;
+
+	lzma_check_update(&info->check, LZMA_CHECK_BEST,
+			(const uint8_t *)(sizes), sizeof(sizes));
+
+	return LZMA_OK;
+}
+
+
+extern LZMA_API(lzma_ret)
+lzma_index_hash_append(lzma_index_hash *index_hash, lzma_vli unpadded_size,
+		lzma_vli uncompressed_size)
+{
+	// Validate the arguments.
+	if (index_hash->sequence != SEQ_BLOCK
+			|| unpadded_size < UNPADDED_SIZE_MIN
+			|| unpadded_size > UNPADDED_SIZE_MAX
+			|| uncompressed_size > LZMA_VLI_MAX)
+		return LZMA_PROG_ERROR;
+
+	// Update the hash.
+	return_if_error(hash_append(&index_hash->blocks,
+			unpadded_size, uncompressed_size));
+
+	// Validate the properties of *info are still in allowed limits.
+	if (index_hash->blocks.blocks_size > LZMA_VLI_MAX
+			|| index_hash->blocks.uncompressed_size > LZMA_VLI_MAX
+			|| index_size(index_hash->blocks.count,
+					index_hash->blocks.index_list_size)
+				> LZMA_BACKWARD_SIZE_MAX
+			|| index_stream_size(index_hash->blocks.blocks_size,
+					index_hash->blocks.count,
+					index_hash->blocks.index_list_size)
+				> LZMA_VLI_MAX)
+		return LZMA_DATA_ERROR;
+
+	return LZMA_OK;
+}
+
+
+extern LZMA_API(lzma_ret)
+lzma_index_hash_decode(lzma_index_hash *index_hash, const uint8_t *in,
+		size_t *in_pos, size_t in_size)
+{
+	size_t in_start;
+	lzma_ret ret;
+
+	// Catch zero input buffer here, because in contrast to Index encoder
+	// and decoder functions, applications call this function directly
+	// instead of via lzma_code(), which does the buffer checking.
+	if (*in_pos >= in_size)
+		return LZMA_BUF_ERROR;
+
+	// NOTE: This function has many similarities to index_encode() and
+	// index_decode() functions found from index_encoder.c and
+	// index_decoder.c. See the comments especially in index_encoder.c.
+	in_start = *in_pos;
+	ret = LZMA_OK;
+
+	while (*in_pos < in_size)
+	switch (index_hash->sequence) {
+	case SEQ_BLOCK:
+		// Check the Index Indicator is present.
+		if (in[(*in_pos)++] != 0x00)
+			return LZMA_DATA_ERROR;
+
+		index_hash->sequence = SEQ_COUNT;
+		break;
+
+	case SEQ_COUNT: {
+		ret = lzma_vli_decode(&index_hash->remaining,
+				&index_hash->pos, in, in_pos, in_size);
+		if (ret != LZMA_STREAM_END)
+			goto out;
+
+		// The count must match the count of the Blocks decoded.
+		if (index_hash->remaining != index_hash->blocks.count)
+			return LZMA_DATA_ERROR;
+
+		ret = LZMA_OK;
+		index_hash->pos = 0;
+
+		// Handle the special case when there are no Blocks.
+		index_hash->sequence = index_hash->remaining == 0
+				? SEQ_PADDING_INIT : SEQ_UNPADDED;
+		break;
+	}
+
+	case SEQ_UNPADDED:
+	case SEQ_UNCOMPRESSED: {
+		lzma_vli *size = index_hash->sequence == SEQ_UNPADDED
+				? &index_hash->unpadded_size
+				: &index_hash->uncompressed_size;
+
+		ret = lzma_vli_decode(size, &index_hash->pos,
+				in, in_pos, in_size);
+		if (ret != LZMA_STREAM_END)
+			goto out;
+
+		ret = LZMA_OK;
+		index_hash->pos = 0;
+
+		if (index_hash->sequence == SEQ_UNPADDED) {
+			if (index_hash->unpadded_size < UNPADDED_SIZE_MIN
+					|| index_hash->unpadded_size
+						> UNPADDED_SIZE_MAX)
+				return LZMA_DATA_ERROR;
+
+			index_hash->sequence = SEQ_UNCOMPRESSED;
+		} else {
+			// Update the hash.
+			return_if_error(hash_append(&index_hash->records,
+					index_hash->unpadded_size,
+					index_hash->uncompressed_size));
+
+			// Verify that we don't go over the known sizes. Note
+			// that this validation is simpler than the one used
+			// in lzma_index_hash_append(), because here we know
+			// that values in index_hash->blocks are already
+			// validated and we are fine as long as we don't
+			// exceed them in index_hash->records.
+			if (index_hash->blocks.blocks_size
+					< index_hash->records.blocks_size
+					|| index_hash->blocks.uncompressed_size
+					< index_hash->records.uncompressed_size
+					|| index_hash->blocks.index_list_size
+					< index_hash->records.index_list_size)
+				return LZMA_DATA_ERROR;
+
+			// Check if this was the last Record.
+			index_hash->sequence = --index_hash->remaining == 0
+					? SEQ_PADDING_INIT : SEQ_UNPADDED;
+		}
+
+		break;
+	}
+
+	case SEQ_PADDING_INIT:
+		index_hash->pos = (LZMA_VLI_C(4) - index_size_unpadded(
+				index_hash->records.count,
+				index_hash->records.index_list_size)) & 3;
+		index_hash->sequence = SEQ_PADDING;
+
+	// Fall through
+
+	case SEQ_PADDING:
+		if (index_hash->pos > 0) {
+			--index_hash->pos;
+			if (in[(*in_pos)++] != 0x00)
+				return LZMA_DATA_ERROR;
+
+			break;
+		}
+
+		// Compare the sizes.
+		if (index_hash->blocks.blocks_size
+				!= index_hash->records.blocks_size
+				|| index_hash->blocks.uncompressed_size
+				!= index_hash->records.uncompressed_size
+				|| index_hash->blocks.index_list_size
+				!= index_hash->records.index_list_size)
+			return LZMA_DATA_ERROR;
+
+		// Finish the hashes and compare them.
+		lzma_check_finish(&index_hash->blocks.check, LZMA_CHECK_BEST);
+		lzma_check_finish(&index_hash->records.check, LZMA_CHECK_BEST);
+		if (memcmp(index_hash->blocks.check.buffer.u8,
+				index_hash->records.check.buffer.u8,
+				lzma_check_size(LZMA_CHECK_BEST)) != 0)
+			return LZMA_DATA_ERROR;
+
+		// Finish the CRC32 calculation.
+		index_hash->crc32 = lzma_crc32(in + in_start,
+				*in_pos - in_start, index_hash->crc32);
+
+		index_hash->sequence = SEQ_CRC32;
+
+	// Fall through
+
+	case SEQ_CRC32:
+		do {
+			if (*in_pos == in_size)
+				return LZMA_OK;
+
+			if (((index_hash->crc32 >> (index_hash->pos * 8))
+					& 0xFF) != in[(*in_pos)++])
+				return LZMA_DATA_ERROR;
+
+		} while (++index_hash->pos < 4);
+
+		return LZMA_STREAM_END;
+
+	default:
+		assert(0);
+		return LZMA_PROG_ERROR;
+	}
+
+out:
+	// Update the CRC32,
+	index_hash->crc32 = lzma_crc32(in + in_start,
+			*in_pos - in_start, index_hash->crc32);
+
+	return ret;
+}
diff --git a/Utilities/cmliblzma/liblzma/common/stream_buffer_decoder.c b/Utilities/cmliblzma/liblzma/common/stream_buffer_decoder.c
new file mode 100644
index 0000000..9e2e1da
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/stream_buffer_decoder.c
@@ -0,0 +1,93 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       stream_buffer_decoder.c
+/// \brief      Single-call .xz Stream decoder
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "stream_decoder.h"
+
+
+extern LZMA_API(lzma_ret)
+lzma_stream_buffer_decode(uint64_t *memlimit, uint32_t flags,
+		lzma_allocator *allocator,
+		const uint8_t *in, size_t *in_pos, size_t in_size,
+		uint8_t *out, size_t *out_pos, size_t out_size)
+{
+	lzma_next_coder stream_decoder = LZMA_NEXT_CODER_INIT;
+	lzma_ret ret;
+
+	// Sanity checks
+	if (in_pos == NULL || (in == NULL && *in_pos != in_size)
+			|| *in_pos > in_size || out_pos == NULL
+			|| (out == NULL && *out_pos != out_size)
+			|| *out_pos > out_size)
+		return LZMA_PROG_ERROR;
+
+	// Catch flags that are not allowed in buffer-to-buffer decoding.
+	if (flags & LZMA_TELL_ANY_CHECK)
+		return LZMA_PROG_ERROR;
+
+	// Initialize the Stream decoder.
+	// TODO: We need something to tell the decoder that it can use the
+	// output buffer as workspace, and thus save significant amount of RAM.
+	ret = lzma_stream_decoder_init(
+			&stream_decoder, allocator, *memlimit, flags);
+
+	if (ret == LZMA_OK) {
+		// Save the positions so that we can restore them in case
+		// an error occurs.
+		const size_t in_start = *in_pos;
+		const size_t out_start = *out_pos;
+
+		// Do the actual decoding.
+		ret = stream_decoder.code(stream_decoder.coder, allocator,
+				in, in_pos, in_size, out, out_pos, out_size,
+				LZMA_FINISH);
+
+		if (ret == LZMA_STREAM_END) {
+			ret = LZMA_OK;
+		} else {
+			// Something went wrong, restore the positions.
+			*in_pos = in_start;
+			*out_pos = out_start;
+
+			if (ret == LZMA_OK) {
+				// Either the input was truncated or the
+				// output buffer was too small.
+				assert(*in_pos == in_size
+						|| *out_pos == out_size);
+
+				// If all the input was consumed, then the
+				// input is truncated, even if the output
+				// buffer is also full. This is because
+				// processing the last byte of the Stream
+				// never produces output.
+				if (*in_pos == in_size)
+					ret = LZMA_DATA_ERROR;
+				else
+					ret = LZMA_BUF_ERROR;
+
+			} else if (ret == LZMA_MEMLIMIT_ERROR) {
+				// Let the caller know how much memory would
+				// have been needed.
+				uint64_t memusage;
+				(void)stream_decoder.memconfig(
+						stream_decoder.coder,
+						memlimit, &memusage, 0);
+			}
+		}
+	}
+
+	// Free the decoder memory. This needs to be done even if
+	// initialization fails, because the internal API doesn't
+	// require the initialization function to free its memory on error.
+	lzma_next_end(&stream_decoder, allocator);
+
+	return ret;
+}
diff --git a/Utilities/cmliblzma/liblzma/common/stream_buffer_encoder.c b/Utilities/cmliblzma/liblzma/common/stream_buffer_encoder.c
new file mode 100644
index 0000000..8bca87f
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/stream_buffer_encoder.c
@@ -0,0 +1,140 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       stream_buffer_encoder.c
+/// \brief      Single-call .xz Stream encoder
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "index.h"
+
+
+/// Maximum size of Index that has exactly one Record.
+/// Index Indicator + Number of Records + Record + CRC32 rounded up to
+/// the next multiple of four.
+#define INDEX_BOUND ((1 + 1 + 2 * LZMA_VLI_BYTES_MAX + 4 + 3) & ~3)
+
+/// Stream Header, Stream Footer, and Index
+#define HEADERS_BOUND (2 * LZMA_STREAM_HEADER_SIZE + INDEX_BOUND)
+
+
+extern LZMA_API(size_t)
+lzma_stream_buffer_bound(size_t uncompressed_size)
+{
+	// Get the maximum possible size of a Block.
+	const size_t block_bound = lzma_block_buffer_bound(uncompressed_size);
+	if (block_bound == 0)
+		return 0;
+
+	// Catch the possible integer overflow and also prevent the size of
+	// the Stream exceeding LZMA_VLI_MAX (theoretically possible on
+	// 64-bit systems).
+	if (my_min(SIZE_MAX, LZMA_VLI_MAX) - block_bound < HEADERS_BOUND)
+		return 0;
+
+	return block_bound + HEADERS_BOUND;
+}
+
+
+extern LZMA_API(lzma_ret)
+lzma_stream_buffer_encode(lzma_filter *filters, lzma_check check,
+		lzma_allocator *allocator, const uint8_t *in, size_t in_size,
+		uint8_t *out, size_t *out_pos_ptr, size_t out_size)
+{
+	lzma_stream_flags stream_flags = { 0 };
+	lzma_block block = { 0 };
+	size_t out_pos;
+
+	// Sanity checks
+	if (filters == NULL || (unsigned int)(check) > LZMA_CHECK_ID_MAX
+			|| (in == NULL && in_size != 0) || out == NULL
+			|| out_pos_ptr == NULL || *out_pos_ptr > out_size)
+		return LZMA_PROG_ERROR;
+
+	if (!lzma_check_is_supported(check))
+		return LZMA_UNSUPPORTED_CHECK;
+
+	// Note for the paranoids: Index encoder prevents the Stream from
+	// getting too big and still being accepted with LZMA_OK, and Block
+	// encoder catches if the input is too big. So we don't need to
+	// separately check if the buffers are too big.
+
+	// Use a local copy. We update *out_pos_ptr only if everything
+	// succeeds.
+	out_pos = *out_pos_ptr;
+
+	// Check that there's enough space for both Stream Header and
+	// Stream Footer.
+	if (out_size - out_pos <= 2 * LZMA_STREAM_HEADER_SIZE)
+		return LZMA_BUF_ERROR;
+
+	// Reserve space for Stream Footer so we don't need to check for
+	// available space again before encoding Stream Footer.
+	out_size -= LZMA_STREAM_HEADER_SIZE;
+
+	// Encode the Stream Header.
+	stream_flags.check = check;
+
+	if (lzma_stream_header_encode(&stream_flags, out + out_pos)
+			!= LZMA_OK)
+		return LZMA_PROG_ERROR;
+
+	out_pos += LZMA_STREAM_HEADER_SIZE;
+
+	// Encode a Block but only if there is at least one byte of input.
+	block.check = check;
+	block.filters = filters;
+
+	if (in_size > 0)
+		return_if_error(lzma_block_buffer_encode(&block, allocator,
+				in, in_size, out, &out_pos, out_size));
+
+	// Index
+	{
+		lzma_ret ret;
+
+		// Create an Index. It will have one Record if there was
+		// at least one byte of input to encode. Otherwise the
+		// Index will be empty.
+		lzma_index *i = lzma_index_init(allocator);
+		if (i == NULL)
+			return LZMA_MEM_ERROR;
+
+		ret = LZMA_OK;
+
+		if (in_size > 0)
+			ret = lzma_index_append(i, allocator,
+					lzma_block_unpadded_size(&block),
+					block.uncompressed_size);
+
+		// If adding the Record was successful, encode the Index
+		// and get its size which will be stored into Stream Footer.
+		if (ret == LZMA_OK) {
+			ret = lzma_index_buffer_encode(
+					i, out, &out_pos, out_size);
+
+			stream_flags.backward_size = lzma_index_size(i);
+		}
+
+		lzma_index_end(i, allocator);
+
+		if (ret != LZMA_OK)
+			return ret;
+	}
+
+	// Stream Footer. We have already reserved space for this.
+	if (lzma_stream_footer_encode(&stream_flags, out + out_pos)
+			!= LZMA_OK)
+		return LZMA_PROG_ERROR;
+
+	out_pos += LZMA_STREAM_HEADER_SIZE;
+
+	// Everything went fine, make the new output position available
+	// to the application.
+	*out_pos_ptr = out_pos;
+	return LZMA_OK;
+}
diff --git a/Utilities/cmliblzma/liblzma/common/stream_decoder.c b/Utilities/cmliblzma/liblzma/common/stream_decoder.c
new file mode 100644
index 0000000..5e9a220
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/stream_decoder.c
@@ -0,0 +1,459 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       stream_decoder.c
+/// \brief      Decodes .xz Streams
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "stream_decoder.h"
+#include "block_decoder.h"
+
+
+struct lzma_coder_s {
+	enum {
+		SEQ_STREAM_HEADER,
+		SEQ_BLOCK_HEADER,
+		SEQ_BLOCK,
+		SEQ_INDEX,
+		SEQ_STREAM_FOOTER,
+		SEQ_STREAM_PADDING,
+	} sequence;
+
+	/// Block or Metadata decoder. This takes little memory and the same
+	/// data structure can be used to decode every Block Header, so it's
+	/// a good idea to have a separate lzma_next_coder structure for it.
+	lzma_next_coder block_decoder;
+
+	/// Block options decoded by the Block Header decoder and used by
+	/// the Block decoder.
+	lzma_block block_options;
+
+	/// Stream Flags from Stream Header
+	lzma_stream_flags stream_flags;
+
+	/// Index is hashed so that it can be compared to the sizes of Blocks
+	/// with O(1) memory usage.
+	lzma_index_hash *index_hash;
+
+	/// Memory usage limit
+	uint64_t memlimit;
+
+	/// Amount of memory actually needed (only an estimate)
+	uint64_t memusage;
+
+	/// If true, LZMA_NO_CHECK is returned if the Stream has
+	/// no integrity check.
+	bool tell_no_check;
+
+	/// If true, LZMA_UNSUPPORTED_CHECK is returned if the Stream has
+	/// an integrity check that isn't supported by this liblzma build.
+	bool tell_unsupported_check;
+
+	/// If true, LZMA_GET_CHECK is returned after decoding Stream Header.
+	bool tell_any_check;
+
+	/// If true, we will decode concatenated Streams that possibly have
+	/// Stream Padding between or after them. LZMA_STREAM_END is returned
+	/// once the application isn't giving us any new input, and we aren't
+	/// in the middle of a Stream, and possible Stream Padding is a
+	/// multiple of four bytes.
+	bool concatenated;
+
+	/// When decoding concatenated Streams, this is true as long as we
+	/// are decoding the first Stream. This is needed to avoid misleading
+	/// LZMA_FORMAT_ERROR in case the later Streams don't have valid magic
+	/// bytes.
+	bool first_stream;
+
+	/// Write position in buffer[] and position in Stream Padding
+	size_t pos;
+
+	/// Buffer to hold Stream Header, Block Header, and Stream Footer.
+	/// Block Header has biggest maximum size.
+	uint8_t buffer[LZMA_BLOCK_HEADER_SIZE_MAX];
+};
+
+
+static lzma_ret
+stream_decoder_reset(lzma_coder *coder, lzma_allocator *allocator)
+{
+	// Initialize the Index hash used to verify the Index.
+	coder->index_hash = lzma_index_hash_init(coder->index_hash, allocator);
+	if (coder->index_hash == NULL)
+		return LZMA_MEM_ERROR;
+
+	// Reset the rest of the variables.
+	coder->sequence = SEQ_STREAM_HEADER;
+	coder->pos = 0;
+
+	return LZMA_OK;
+}
+
+
+static lzma_ret
+stream_decode(lzma_coder *coder, lzma_allocator *allocator,
+		const uint8_t *LZMA_RESTRICT in, size_t *LZMA_RESTRICT in_pos,
+		size_t in_size, uint8_t *LZMA_RESTRICT out,
+		size_t *LZMA_RESTRICT out_pos, size_t out_size, lzma_action action)
+{
+	// When decoding the actual Block, it may be able to produce more
+	// output even if we don't give it any new input.
+	while (true)
+	switch (coder->sequence) {
+	case SEQ_STREAM_HEADER: {
+		lzma_ret ret;
+
+		// Copy the Stream Header to the internal buffer.
+		lzma_bufcpy(in, in_pos, in_size, coder->buffer, &coder->pos,
+				LZMA_STREAM_HEADER_SIZE);
+
+		// Return if we didn't get the whole Stream Header yet.
+		if (coder->pos < LZMA_STREAM_HEADER_SIZE)
+			return LZMA_OK;
+
+		coder->pos = 0;
+
+		// Decode the Stream Header.
+		ret = lzma_stream_header_decode(
+				&coder->stream_flags, coder->buffer);
+		if (ret != LZMA_OK)
+			return ret == LZMA_FORMAT_ERROR && !coder->first_stream
+					? LZMA_DATA_ERROR : ret;
+
+		// If we are decoding concatenated Streams, and the later
+		// Streams have invalid Header Magic Bytes, we give
+		// LZMA_DATA_ERROR instead of LZMA_FORMAT_ERROR.
+		coder->first_stream = false;
+
+		// Copy the type of the Check so that Block Header and Block
+		// decoders see it.
+		coder->block_options.check = coder->stream_flags.check;
+
+		// Even if we return LZMA_*_CHECK below, we want
+		// to continue from Block Header decoding.
+		coder->sequence = SEQ_BLOCK_HEADER;
+
+		// Detect if there's no integrity check or if it is
+		// unsupported if those were requested by the application.
+		if (coder->tell_no_check && coder->stream_flags.check
+				== LZMA_CHECK_NONE)
+			return LZMA_NO_CHECK;
+
+		if (coder->tell_unsupported_check
+				&& !lzma_check_is_supported(
+					coder->stream_flags.check))
+			return LZMA_UNSUPPORTED_CHECK;
+
+		if (coder->tell_any_check)
+			return LZMA_GET_CHECK;
+	}
+
+	// Fall through
+
+	case SEQ_BLOCK_HEADER: {
+		lzma_filter filters[LZMA_FILTERS_MAX + 1];
+		uint64_t memusage;
+		lzma_ret ret;
+		size_t i;
+
+		if (*in_pos >= in_size)
+			return LZMA_OK;
+
+		if (coder->pos == 0) {
+			// Detect if it's Index.
+			if (in[*in_pos] == 0x00) {
+				coder->sequence = SEQ_INDEX;
+				break;
+			}
+
+			// Calculate the size of the Block Header. Note that
+			// Block Header decoder wants to see this byte too
+			// so don't advance *in_pos.
+			coder->block_options.header_size
+					= lzma_block_header_size_decode(
+						in[*in_pos]);
+		}
+
+		// Copy the Block Header to the internal buffer.
+		lzma_bufcpy(in, in_pos, in_size, coder->buffer, &coder->pos,
+				coder->block_options.header_size);
+
+		// Return if we didn't get the whole Block Header yet.
+		if (coder->pos < coder->block_options.header_size)
+			return LZMA_OK;
+
+		coder->pos = 0;
+
+		// Version 0 is currently the only possible version.
+		coder->block_options.version = 0;
+
+		// Set up a buffer to hold the filter chain. Block Header
+		// decoder will initialize all members of this array so
+		// we don't need to do it here.
+		coder->block_options.filters = filters;
+
+		// Decode the Block Header.
+		return_if_error(lzma_block_header_decode(&coder->block_options,
+				allocator, coder->buffer));
+
+		// Check the memory usage limit.
+		memusage = lzma_raw_decoder_memusage(filters);
+		if (memusage == UINT64_MAX) {
+			// One or more unknown Filter IDs.
+			ret = LZMA_OPTIONS_ERROR;
+		} else {
+			// Now we can set coder->memusage since we know that
+			// the filter chain is valid. We don't want
+			// lzma_memusage() to return UINT64_MAX in case of
+			// invalid filter chain.
+			coder->memusage = memusage;
+
+			if (memusage > coder->memlimit) {
+				// The chain would need too much memory.
+				ret = LZMA_MEMLIMIT_ERROR;
+			} else {
+				// Memory usage is OK.
+				// Initialize the Block decoder.
+				ret = lzma_block_decoder_init(
+						&coder->block_decoder,
+						allocator,
+						&coder->block_options);
+			}
+		}
+
+		// Free the allocated filter options since they are needed
+		// only to initialize the Block decoder.
+		for (i = 0; i < LZMA_FILTERS_MAX; ++i)
+			lzma_free(filters[i].options, allocator);
+
+		coder->block_options.filters = NULL;
+
+		// Check if memory usage calculation and Block enocoder
+		// initialization succeeded.
+		if (ret != LZMA_OK)
+			return ret;
+
+		coder->sequence = SEQ_BLOCK;
+	}
+
+	// Fall through
+
+	case SEQ_BLOCK: {
+		const lzma_ret ret = coder->block_decoder.code(
+				coder->block_decoder.coder, allocator,
+				in, in_pos, in_size, out, out_pos, out_size,
+				action);
+
+		if (ret != LZMA_STREAM_END)
+			return ret;
+
+		// Block decoded successfully. Add the new size pair to
+		// the Index hash.
+		return_if_error(lzma_index_hash_append(coder->index_hash,
+				lzma_block_unpadded_size(
+					&coder->block_options),
+				coder->block_options.uncompressed_size));
+
+		coder->sequence = SEQ_BLOCK_HEADER;
+		break;
+	}
+
+	case SEQ_INDEX: {
+		lzma_ret ret;
+
+		// If we don't have any input, don't call
+		// lzma_index_hash_decode() since it would return
+		// LZMA_BUF_ERROR, which we must not do here.
+		if (*in_pos >= in_size)
+			return LZMA_OK;
+
+		// Decode the Index and compare it to the hash calculated
+		// from the sizes of the Blocks (if any).
+		ret = lzma_index_hash_decode(coder->index_hash,
+				in, in_pos, in_size);
+		if (ret != LZMA_STREAM_END)
+			return ret;
+
+		coder->sequence = SEQ_STREAM_FOOTER;
+	}
+
+	// Fall through
+
+	case SEQ_STREAM_FOOTER: {
+		lzma_stream_flags footer_flags;
+		lzma_ret ret;
+
+		// Copy the Stream Footer to the internal buffer.
+		lzma_bufcpy(in, in_pos, in_size, coder->buffer, &coder->pos,
+				LZMA_STREAM_HEADER_SIZE);
+
+		// Return if we didn't get the whole Stream Footer yet.
+		if (coder->pos < LZMA_STREAM_HEADER_SIZE)
+			return LZMA_OK;
+
+		coder->pos = 0;
+
+		// Decode the Stream Footer. The decoder gives
+		// LZMA_FORMAT_ERROR if the magic bytes don't match,
+		// so convert that return code to LZMA_DATA_ERROR.
+		ret = lzma_stream_footer_decode(
+				&footer_flags, coder->buffer);
+		if (ret != LZMA_OK)
+			return ret == LZMA_FORMAT_ERROR
+					? LZMA_DATA_ERROR : ret;
+
+		// Check that Index Size stored in the Stream Footer matches
+		// the real size of the Index field.
+		if (lzma_index_hash_size(coder->index_hash)
+				!= footer_flags.backward_size)
+			return LZMA_DATA_ERROR;
+
+		// Compare that the Stream Flags fields are identical in
+		// both Stream Header and Stream Footer.
+		return_if_error(lzma_stream_flags_compare(
+				&coder->stream_flags, &footer_flags));
+
+		if (!coder->concatenated)
+			return LZMA_STREAM_END;
+
+		coder->sequence = SEQ_STREAM_PADDING;
+	}
+
+	// Fall through
+
+	case SEQ_STREAM_PADDING:
+		assert(coder->concatenated);
+
+		// Skip over possible Stream Padding.
+		while (true) {
+			if (*in_pos >= in_size) {
+				// Unless LZMA_FINISH was used, we cannot
+				// know if there's more input coming later.
+				if (action != LZMA_FINISH)
+					return LZMA_OK;
+
+				// Stream Padding must be a multiple of
+				// four bytes.
+				return coder->pos == 0
+						? LZMA_STREAM_END
+						: LZMA_DATA_ERROR;
+			}
+
+			// If the byte is not zero, it probably indicates
+			// beginning of a new Stream (or the file is corrupt).
+			if (in[*in_pos] != 0x00)
+				break;
+
+			++*in_pos;
+			coder->pos = (coder->pos + 1) & 3;
+		}
+
+		// Stream Padding must be a multiple of four bytes (empty
+		// Stream Padding is OK).
+		if (coder->pos != 0) {
+			++*in_pos;
+			return LZMA_DATA_ERROR;
+		}
+
+		// Prepare to decode the next Stream.
+		return_if_error(stream_decoder_reset(coder, allocator));
+		break;
+
+	default:
+		assert(0);
+		return LZMA_PROG_ERROR;
+	}
+
+	// Never reached
+}
+
+
+static void
+stream_decoder_end(lzma_coder *coder, lzma_allocator *allocator)
+{
+	lzma_next_end(&coder->block_decoder, allocator);
+	lzma_index_hash_end(coder->index_hash, allocator);
+	lzma_free(coder, allocator);
+	return;
+}
+
+
+static lzma_check
+stream_decoder_get_check(const lzma_coder *coder)
+{
+	return coder->stream_flags.check;
+}
+
+
+static lzma_ret
+stream_decoder_memconfig(lzma_coder *coder, uint64_t *memusage,
+		uint64_t *old_memlimit, uint64_t new_memlimit)
+{
+	*memusage = coder->memusage;
+	*old_memlimit = coder->memlimit;
+
+	if (new_memlimit != 0) {
+		if (new_memlimit < coder->memusage)
+			return LZMA_MEMLIMIT_ERROR;
+
+		coder->memlimit = new_memlimit;
+	}
+
+	return LZMA_OK;
+}
+
+
+extern lzma_ret
+lzma_stream_decoder_init(lzma_next_coder *next, lzma_allocator *allocator,
+		uint64_t memlimit, uint32_t flags)
+{
+	lzma_next_coder_init(&lzma_stream_decoder_init, next, allocator);
+
+	if (memlimit == 0)
+		return LZMA_PROG_ERROR;
+
+	if (flags & ~LZMA_SUPPORTED_FLAGS)
+		return LZMA_OPTIONS_ERROR;
+
+	if (next->coder == NULL) {
+		next->coder = lzma_alloc(sizeof(lzma_coder), allocator);
+		if (next->coder == NULL)
+			return LZMA_MEM_ERROR;
+
+		next->code = &stream_decode;
+		next->end = &stream_decoder_end;
+		next->get_check = &stream_decoder_get_check;
+		next->memconfig = &stream_decoder_memconfig;
+
+		next->coder->block_decoder = LZMA_NEXT_CODER_INIT;
+		next->coder->index_hash = NULL;
+	}
+
+	next->coder->memlimit = memlimit;
+	next->coder->memusage = LZMA_MEMUSAGE_BASE;
+	next->coder->tell_no_check = (flags & LZMA_TELL_NO_CHECK) != 0;
+	next->coder->tell_unsupported_check
+			= (flags & LZMA_TELL_UNSUPPORTED_CHECK) != 0;
+	next->coder->tell_any_check = (flags & LZMA_TELL_ANY_CHECK) != 0;
+	next->coder->concatenated = (flags & LZMA_CONCATENATED) != 0;
+	next->coder->first_stream = true;
+
+	return stream_decoder_reset(next->coder, allocator);
+}
+
+
+extern LZMA_API(lzma_ret)
+lzma_stream_decoder(lzma_stream *strm, uint64_t memlimit, uint32_t flags)
+{
+	lzma_next_strm_init2(lzma_stream_decoder_init, strm, memlimit, flags);
+
+	strm->internal->supported_actions[LZMA_RUN] = true;
+	strm->internal->supported_actions[LZMA_FINISH] = true;
+
+	return LZMA_OK;
+}
diff --git a/Utilities/cmliblzma/liblzma/common/stream_decoder.h b/Utilities/cmliblzma/liblzma/common/stream_decoder.h
new file mode 100644
index 0000000..e54ac28
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/stream_decoder.h
@@ -0,0 +1,21 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       stream_decoder.h
+/// \brief      Decodes .xz Streams
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#ifndef LZMA_STREAM_DECODER_H
+#define LZMA_STREAM_DECODER_H
+
+#include "common.h"
+
+extern lzma_ret lzma_stream_decoder_init(lzma_next_coder *next,
+		lzma_allocator *allocator, uint64_t memlimit, uint32_t flags);
+
+#endif
diff --git a/Utilities/cmliblzma/liblzma/common/stream_encoder.c b/Utilities/cmliblzma/liblzma/common/stream_encoder.c
new file mode 100644
index 0000000..1ba45ac
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/stream_encoder.c
@@ -0,0 +1,338 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       stream_encoder.c
+/// \brief      Encodes .xz Streams
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "stream_encoder.h"
+#include "block_encoder.h"
+#include "index_encoder.h"
+
+
+struct lzma_coder_s {
+	enum {
+		SEQ_STREAM_HEADER,
+		SEQ_BLOCK_INIT,
+		SEQ_BLOCK_HEADER,
+		SEQ_BLOCK_ENCODE,
+		SEQ_INDEX_ENCODE,
+		SEQ_STREAM_FOOTER,
+	} sequence;
+
+	/// True if Block encoder has been initialized by
+	/// lzma_stream_encoder_init() or stream_encoder_update()
+	/// and thus doesn't need to be initialized in stream_encode().
+	bool block_encoder_is_initialized;
+
+	/// Block
+	lzma_next_coder block_encoder;
+
+	/// Options for the Block encoder
+	lzma_block block_options;
+
+	/// The filter chain currently in use
+	lzma_filter filters[LZMA_FILTERS_MAX + 1];
+
+	/// Index encoder. This is separate from Block encoder, because this
+	/// doesn't take much memory, and when encoding multiple Streams
+	/// with the same encoding options we avoid reallocating memory.
+	lzma_next_coder index_encoder;
+
+	/// Index to hold sizes of the Blocks
+	lzma_index *index;
+
+	/// Read position in buffer[]
+	size_t buffer_pos;
+
+	/// Total number of bytes in buffer[]
+	size_t buffer_size;
+
+	/// Buffer to hold Stream Header, Block Header, and Stream Footer.
+	/// Block Header has biggest maximum size.
+	uint8_t buffer[LZMA_BLOCK_HEADER_SIZE_MAX];
+};
+
+
+static lzma_ret
+block_encoder_init(lzma_coder *coder, lzma_allocator *allocator)
+{
+	// Prepare the Block options. Even though Block encoder doesn't need
+	// compressed_size, uncompressed_size, and header_size to be
+	// initialized, it is a good idea to do it here, because this way
+	// we catch if someone gave us Filter ID that cannot be used in
+	// Blocks/Streams.
+	coder->block_options.compressed_size = LZMA_VLI_UNKNOWN;
+	coder->block_options.uncompressed_size = LZMA_VLI_UNKNOWN;
+
+	return_if_error(lzma_block_header_size(&coder->block_options));
+
+	// Initialize the actual Block encoder.
+	return lzma_block_encoder_init(&coder->block_encoder, allocator,
+			&coder->block_options);
+}
+
+
+static lzma_ret
+stream_encode(lzma_coder *coder, lzma_allocator *allocator,
+		const uint8_t *LZMA_RESTRICT in, size_t *LZMA_RESTRICT in_pos,
+		size_t in_size, uint8_t *LZMA_RESTRICT out,
+		size_t *LZMA_RESTRICT out_pos, size_t out_size, lzma_action action)
+{
+	// Main loop
+	while (*out_pos < out_size)
+	switch (coder->sequence) {
+	case SEQ_STREAM_HEADER:
+	case SEQ_BLOCK_HEADER:
+	case SEQ_STREAM_FOOTER:
+		lzma_bufcpy(coder->buffer, &coder->buffer_pos,
+				coder->buffer_size, out, out_pos, out_size);
+		if (coder->buffer_pos < coder->buffer_size)
+			return LZMA_OK;
+
+		if (coder->sequence == SEQ_STREAM_FOOTER)
+			return LZMA_STREAM_END;
+
+		coder->buffer_pos = 0;
+		++coder->sequence;
+		break;
+
+	case SEQ_BLOCK_INIT: {
+		if (*in_pos == in_size) {
+			// If we are requested to flush or finish the current
+			// Block, return LZMA_STREAM_END immediately since
+			// there's nothing to do.
+			if (action != LZMA_FINISH)
+				return action == LZMA_RUN
+						? LZMA_OK : LZMA_STREAM_END;
+
+			// The application had used LZMA_FULL_FLUSH to finish
+			// the previous Block, but now wants to finish without
+			// encoding new data, or it is simply creating an
+			// empty Stream with no Blocks.
+			//
+			// Initialize the Index encoder, and continue to
+			// actually encoding the Index.
+			return_if_error(lzma_index_encoder_init(
+					&coder->index_encoder, allocator,
+					coder->index));
+			coder->sequence = SEQ_INDEX_ENCODE;
+			break;
+		}
+
+		// Initialize the Block encoder unless it was already
+		// initialized by lzma_stream_encoder_init() or
+		// stream_encoder_update().
+		if (!coder->block_encoder_is_initialized)
+			return_if_error(block_encoder_init(coder, allocator));
+
+		// Make it false so that we don't skip the initialization
+		// with the next Block.
+		coder->block_encoder_is_initialized = false;
+
+		// Encode the Block Header. This shouldn't fail since we have
+		// already initialized the Block encoder.
+		if (lzma_block_header_encode(&coder->block_options,
+				coder->buffer) != LZMA_OK)
+			return LZMA_PROG_ERROR;
+
+		coder->buffer_size = coder->block_options.header_size;
+		coder->sequence = SEQ_BLOCK_HEADER;
+		break;
+	}
+
+	case SEQ_BLOCK_ENCODE: {
+		lzma_vli unpadded_size;
+
+		static const lzma_action convert[4] = {
+			LZMA_RUN,
+			LZMA_SYNC_FLUSH,
+			LZMA_FINISH,
+			LZMA_FINISH,
+		};
+
+		const lzma_ret ret = coder->block_encoder.code(
+				coder->block_encoder.coder, allocator,
+				in, in_pos, in_size,
+				out, out_pos, out_size, convert[action]);
+		if (ret != LZMA_STREAM_END || action == LZMA_SYNC_FLUSH)
+			return ret;
+
+		// Add a new Index Record.
+		unpadded_size = lzma_block_unpadded_size(
+				&coder->block_options);
+		assert(unpadded_size != 0);
+		return_if_error(lzma_index_append(coder->index, allocator,
+				unpadded_size,
+				coder->block_options.uncompressed_size));
+
+		coder->sequence = SEQ_BLOCK_INIT;
+		break;
+	}
+
+	case SEQ_INDEX_ENCODE: {
+		const lzma_stream_flags stream_flags = {
+			0,
+			lzma_index_size(coder->index),
+			coder->block_options.check,
+		};
+
+		// Call the Index encoder. It doesn't take any input, so
+		// those pointers can be NULL.
+		const lzma_ret ret = coder->index_encoder.code(
+				coder->index_encoder.coder, allocator,
+				NULL, NULL, 0,
+				out, out_pos, out_size, LZMA_RUN);
+		if (ret != LZMA_STREAM_END)
+			return ret;
+
+		// Encode the Stream Footer into coder->buffer.
+
+		if (lzma_stream_footer_encode(&stream_flags, coder->buffer)
+				!= LZMA_OK)
+			return LZMA_PROG_ERROR;
+
+		coder->buffer_size = LZMA_STREAM_HEADER_SIZE;
+		coder->sequence = SEQ_STREAM_FOOTER;
+		break;
+	}
+
+	default:
+		assert(0);
+		return LZMA_PROG_ERROR;
+	}
+
+	return LZMA_OK;
+}
+
+
+static void
+stream_encoder_end(lzma_coder *coder, lzma_allocator *allocator)
+{
+	size_t i;
+
+	lzma_next_end(&coder->block_encoder, allocator);
+	lzma_next_end(&coder->index_encoder, allocator);
+	lzma_index_end(coder->index, allocator);
+
+	for (i = 0; coder->filters[i].id != LZMA_VLI_UNKNOWN; ++i)
+		lzma_free(coder->filters[i].options, allocator);
+
+	lzma_free(coder, allocator);
+	return;
+}
+
+
+static lzma_ret
+stream_encoder_update(lzma_coder *coder, lzma_allocator *allocator,
+		const lzma_filter *filters,
+		const lzma_filter *reversed_filters)
+{
+	size_t i;
+
+	if (coder->sequence <= SEQ_BLOCK_INIT) {
+		lzma_ret ret;
+
+		// There is no incomplete Block waiting to be finished,
+		// thus we can change the whole filter chain. Start by
+		// trying to initialize the Block encoder with the new
+		// chain. This way we detect if the chain is valid.
+		coder->block_encoder_is_initialized = false;
+		coder->block_options.filters = (lzma_filter *)(filters);
+		ret = block_encoder_init(coder, allocator);
+		coder->block_options.filters = coder->filters;
+		if (ret != LZMA_OK)
+			return ret;
+
+		coder->block_encoder_is_initialized = true;
+
+	} else if (coder->sequence <= SEQ_BLOCK_ENCODE) {
+		// We are in the middle of a Block. Try to update only
+		// the filter-specific options.
+		return_if_error(coder->block_encoder.update(
+				coder->block_encoder.coder, allocator,
+				filters, reversed_filters));
+	} else {
+		// Trying to update the filter chain when we are already
+		// encoding Index or Stream Footer.
+		return LZMA_PROG_ERROR;
+	}
+
+	// Free the copy of the old chain and make a copy of the new chain.
+	for (i = 0; coder->filters[i].id != LZMA_VLI_UNKNOWN; ++i)
+		lzma_free(coder->filters[i].options, allocator);
+
+	return lzma_filters_copy(filters, coder->filters, allocator);
+}
+
+
+extern lzma_ret
+lzma_stream_encoder_init(lzma_next_coder *next, lzma_allocator *allocator,
+		const lzma_filter *filters, lzma_check check)
+{
+	lzma_stream_flags stream_flags = { 0, 0, check };
+
+	lzma_next_coder_init(&lzma_stream_encoder_init, next, allocator);
+
+	if (filters == NULL)
+		return LZMA_PROG_ERROR;
+
+	if (next->coder == NULL) {
+		next->coder = lzma_alloc(sizeof(lzma_coder), allocator);
+		if (next->coder == NULL)
+			return LZMA_MEM_ERROR;
+
+		next->code = &stream_encode;
+		next->end = &stream_encoder_end;
+		next->update = &stream_encoder_update;
+
+		next->coder->filters[0].id = LZMA_VLI_UNKNOWN;
+		next->coder->block_encoder = LZMA_NEXT_CODER_INIT;
+		next->coder->index_encoder = LZMA_NEXT_CODER_INIT;
+		next->coder->index = NULL;
+	}
+
+	// Basic initializations
+	next->coder->sequence = SEQ_STREAM_HEADER;
+	next->coder->block_options.version = 0;
+	next->coder->block_options.check = check;
+
+	// Initialize the Index
+	lzma_index_end(next->coder->index, allocator);
+	next->coder->index = lzma_index_init(allocator);
+	if (next->coder->index == NULL)
+		return LZMA_MEM_ERROR;
+
+	// Encode the Stream Header
+	return_if_error(lzma_stream_header_encode(
+			&stream_flags, next->coder->buffer));
+
+	next->coder->buffer_pos = 0;
+	next->coder->buffer_size = LZMA_STREAM_HEADER_SIZE;
+
+	// Initialize the Block encoder. This way we detect unsupported
+	// filter chains when initializing the Stream encoder instead of
+	// giving an error after Stream Header has already written out.
+	return stream_encoder_update(
+			next->coder, allocator, filters, NULL);
+}
+
+
+extern LZMA_API(lzma_ret)
+lzma_stream_encoder(lzma_stream *strm,
+		const lzma_filter *filters, lzma_check check)
+{
+	lzma_next_strm_init2(lzma_stream_encoder_init, strm, filters, check);
+
+	strm->internal->supported_actions[LZMA_RUN] = true;
+	strm->internal->supported_actions[LZMA_SYNC_FLUSH] = true;
+	strm->internal->supported_actions[LZMA_FULL_FLUSH] = true;
+	strm->internal->supported_actions[LZMA_FINISH] = true;
+
+	return LZMA_OK;
+}
diff --git a/Utilities/cmliblzma/liblzma/common/stream_encoder.h b/Utilities/cmliblzma/liblzma/common/stream_encoder.h
new file mode 100644
index 0000000..46a7aed
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/stream_encoder.h
@@ -0,0 +1,23 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       stream_encoder.h
+/// \brief      Encodes .xz Streams
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#ifndef LZMA_STREAM_ENCODER_H
+#define LZMA_STREAM_ENCODER_H
+
+#include "common.h"
+
+
+extern lzma_ret lzma_stream_encoder_init(
+		lzma_next_coder *next, lzma_allocator *allocator,
+		const lzma_filter *filters, lzma_check check);
+
+#endif
diff --git a/Utilities/cmliblzma/liblzma/common/stream_flags_common.c b/Utilities/cmliblzma/liblzma/common/stream_flags_common.c
new file mode 100644
index 0000000..fbe8eb8
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/stream_flags_common.c
@@ -0,0 +1,47 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       stream_flags_common.c
+/// \brief      Common stuff for Stream flags coders
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "stream_flags_common.h"
+
+
+const uint8_t lzma_header_magic[6] = { 0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00 };
+const uint8_t lzma_footer_magic[2] = { 0x59, 0x5A };
+
+
+extern LZMA_API(lzma_ret)
+lzma_stream_flags_compare(
+		const lzma_stream_flags *a, const lzma_stream_flags *b)
+{
+	// We can compare only version 0 structures.
+	if (a->version != 0 || b->version != 0)
+		return LZMA_OPTIONS_ERROR;
+
+	// Check type
+	if ((unsigned int)(a->check) > LZMA_CHECK_ID_MAX
+			|| (unsigned int)(b->check) > LZMA_CHECK_ID_MAX)
+		return LZMA_PROG_ERROR;
+
+	if (a->check != b->check)
+		return LZMA_DATA_ERROR;
+
+	// Backward Sizes are compared only if they are known in both.
+	if (a->backward_size != LZMA_VLI_UNKNOWN
+			&& b->backward_size != LZMA_VLI_UNKNOWN) {
+		if (!is_backward_size_valid(a) || !is_backward_size_valid(b))
+			return LZMA_PROG_ERROR;
+
+		if (a->backward_size != b->backward_size)
+			return LZMA_DATA_ERROR;
+	}
+
+	return LZMA_OK;
+}
diff --git a/Utilities/cmliblzma/liblzma/common/stream_flags_common.h b/Utilities/cmliblzma/liblzma/common/stream_flags_common.h
new file mode 100644
index 0000000..9f3122a
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/stream_flags_common.h
@@ -0,0 +1,33 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       stream_flags_common.h
+/// \brief      Common stuff for Stream flags coders
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#ifndef LZMA_STREAM_FLAGS_COMMON_H
+#define LZMA_STREAM_FLAGS_COMMON_H
+
+#include "common.h"
+
+/// Size of the Stream Flags field
+#define LZMA_STREAM_FLAGS_SIZE 2
+
+extern const uint8_t lzma_header_magic[6];
+extern const uint8_t lzma_footer_magic[2];
+
+
+static inline bool
+is_backward_size_valid(const lzma_stream_flags *options)
+{
+	return options->backward_size >= LZMA_BACKWARD_SIZE_MIN
+			&& options->backward_size <= LZMA_BACKWARD_SIZE_MAX
+			&& (options->backward_size & 3) == 0;
+}
+
+#endif
diff --git a/Utilities/cmliblzma/liblzma/common/stream_flags_decoder.c b/Utilities/cmliblzma/liblzma/common/stream_flags_decoder.c
new file mode 100644
index 0000000..8cf48a4
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/stream_flags_decoder.c
@@ -0,0 +1,86 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       stream_flags_decoder.c
+/// \brief      Decodes Stream Header and Stream Footer from .xz files
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "stream_flags_common.h"
+
+
+static bool
+stream_flags_decode(lzma_stream_flags *options, const uint8_t *in)
+{
+	// Reserved bits must be unset.
+	if (in[0] != 0x00 || (in[1] & 0xF0))
+		return true;
+
+	options->version = 0;
+	options->check = in[1] & 0x0F;
+
+	return false;
+}
+
+
+extern LZMA_API(lzma_ret)
+lzma_stream_header_decode(lzma_stream_flags *options, const uint8_t *in)
+{
+	uint32_t crc;
+
+	// Magic
+	if (memcmp(in, lzma_header_magic, sizeof(lzma_header_magic)) != 0)
+		return LZMA_FORMAT_ERROR;
+
+	// Verify the CRC32 so we can distinguish between corrupt
+	// and unsupported files.
+	crc = lzma_crc32(in + sizeof(lzma_header_magic),
+			LZMA_STREAM_FLAGS_SIZE, 0);
+	if (crc != unaligned_read32le(in + sizeof(lzma_header_magic)
+			+ LZMA_STREAM_FLAGS_SIZE))
+		return LZMA_DATA_ERROR;
+
+	// Stream Flags
+	if (stream_flags_decode(options, in + sizeof(lzma_header_magic)))
+		return LZMA_OPTIONS_ERROR;
+
+	// Set Backward Size to indicate unknown value. That way
+	// lzma_stream_flags_compare() can be used to compare Stream Header
+	// and Stream Footer while keeping it useful also for comparing
+	// two Stream Footers.
+	options->backward_size = LZMA_VLI_UNKNOWN;
+
+	return LZMA_OK;
+}
+
+
+extern LZMA_API(lzma_ret)
+lzma_stream_footer_decode(lzma_stream_flags *options, const uint8_t *in)
+{
+	uint32_t crc;
+
+	// Magic
+	if (memcmp(in + sizeof(uint32_t) * 2 + LZMA_STREAM_FLAGS_SIZE,
+			lzma_footer_magic, sizeof(lzma_footer_magic)) != 0)
+		return LZMA_FORMAT_ERROR;
+
+	// CRC32
+	crc = lzma_crc32(in + sizeof(uint32_t),
+			sizeof(uint32_t) + LZMA_STREAM_FLAGS_SIZE, 0);
+	if (crc != unaligned_read32le(in))
+		return LZMA_DATA_ERROR;
+
+	// Stream Flags
+	if (stream_flags_decode(options, in + sizeof(uint32_t) * 2))
+		return LZMA_OPTIONS_ERROR;
+
+	// Backward Size
+	options->backward_size = unaligned_read32le(in + sizeof(uint32_t));
+	options->backward_size = (options->backward_size + 1) * 4;
+
+	return LZMA_OK;
+}
diff --git a/Utilities/cmliblzma/liblzma/common/stream_flags_encoder.c b/Utilities/cmliblzma/liblzma/common/stream_flags_encoder.c
new file mode 100644
index 0000000..290339e
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/stream_flags_encoder.c
@@ -0,0 +1,90 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       stream_flags_encoder.c
+/// \brief      Encodes Stream Header and Stream Footer for .xz files
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "stream_flags_common.h"
+
+
+static bool
+stream_flags_encode(const lzma_stream_flags *options, uint8_t *out)
+{
+	if ((unsigned int)(options->check) > LZMA_CHECK_ID_MAX)
+		return true;
+
+	out[0] = 0x00;
+	out[1] = options->check;
+
+	return false;
+}
+
+
+extern LZMA_API(lzma_ret)
+lzma_stream_header_encode(const lzma_stream_flags *options, uint8_t *out)
+{
+	uint32_t crc;
+
+	assert(sizeof(lzma_header_magic) + LZMA_STREAM_FLAGS_SIZE
+			+ 4 == LZMA_STREAM_HEADER_SIZE);
+
+	if (options->version != 0)
+		return LZMA_OPTIONS_ERROR;
+
+	// Magic
+	memcpy(out, lzma_header_magic, sizeof(lzma_header_magic));
+
+	// Stream Flags
+	if (stream_flags_encode(options, out + sizeof(lzma_header_magic)))
+		return LZMA_PROG_ERROR;
+
+	// CRC32 of the Stream Header
+	crc = lzma_crc32(out + sizeof(lzma_header_magic),
+			LZMA_STREAM_FLAGS_SIZE, 0);
+
+	unaligned_write32le(out + sizeof(lzma_header_magic)
+			+ LZMA_STREAM_FLAGS_SIZE, crc);
+
+	return LZMA_OK;
+}
+
+
+extern LZMA_API(lzma_ret)
+lzma_stream_footer_encode(const lzma_stream_flags *options, uint8_t *out)
+{
+	uint32_t crc;
+
+	assert(2 * 4 + LZMA_STREAM_FLAGS_SIZE + sizeof(lzma_footer_magic)
+			== LZMA_STREAM_HEADER_SIZE);
+
+	if (options->version != 0)
+		return LZMA_OPTIONS_ERROR;
+
+	// Backward Size
+	if (!is_backward_size_valid(options))
+		return LZMA_PROG_ERROR;
+
+	unaligned_write32le(out + 4, options->backward_size / 4 - 1);
+
+	// Stream Flags
+	if (stream_flags_encode(options, out + 2 * 4))
+		return LZMA_PROG_ERROR;
+
+	// CRC32
+	crc = lzma_crc32(
+			out + 4, 4 + LZMA_STREAM_FLAGS_SIZE, 0);
+
+	unaligned_write32le(out, crc);
+
+	// Magic
+	memcpy(out + 2 * 4 + LZMA_STREAM_FLAGS_SIZE,
+			lzma_footer_magic, sizeof(lzma_footer_magic));
+
+	return LZMA_OK;
+}
diff --git a/Utilities/cmliblzma/liblzma/common/vli_decoder.c b/Utilities/cmliblzma/liblzma/common/vli_decoder.c
new file mode 100644
index 0000000..1c66384
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/vli_decoder.c
@@ -0,0 +1,86 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       vli_decoder.c
+/// \brief      Decodes variable-length integers
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "common.h"
+
+
+extern LZMA_API(lzma_ret)
+lzma_vli_decode(lzma_vli *LZMA_RESTRICT vli, size_t *vli_pos,
+		const uint8_t *LZMA_RESTRICT in, size_t *LZMA_RESTRICT in_pos,
+		size_t in_size)
+{
+	// If we haven't been given vli_pos, work in single-call mode.
+	size_t vli_pos_internal = 0;
+	if (vli_pos == NULL) {
+		vli_pos = &vli_pos_internal;
+		*vli = 0;
+
+		// If there's no input, use LZMA_DATA_ERROR. This way it is
+		// easy to decode VLIs from buffers that have known size,
+		// and get the correct error code in case the buffer is
+		// too short.
+		if (*in_pos >= in_size)
+			return LZMA_DATA_ERROR;
+
+	} else {
+		// Initialize *vli when starting to decode a new integer.
+		if (*vli_pos == 0)
+			*vli = 0;
+
+		// Validate the arguments.
+		if (*vli_pos >= LZMA_VLI_BYTES_MAX
+				|| (*vli >> (*vli_pos * 7)) != 0)
+			return LZMA_PROG_ERROR;;
+
+		if (*in_pos >= in_size)
+			return LZMA_BUF_ERROR;
+	}
+
+	do {
+		// Read the next byte. Use a temporary variable so that we
+		// can update *in_pos immediately.
+		const uint8_t byte = in[*in_pos];
+		++*in_pos;
+
+		// Add the newly read byte to *vli.
+		*vli += (lzma_vli)(byte & 0x7F) << (*vli_pos * 7);
+		++*vli_pos;
+
+		// Check if this is the last byte of a multibyte integer.
+		if ((byte & 0x80) == 0) {
+			// We don't allow using variable-length integers as
+			// padding i.e. the encoding must use the most the
+			// compact form.
+			if (byte == 0x00 && *vli_pos > 1)
+				return LZMA_DATA_ERROR;
+
+			return vli_pos == &vli_pos_internal
+					? LZMA_OK : LZMA_STREAM_END;
+		}
+
+		// There is at least one more byte coming. If we have already
+		// read maximum number of bytes, the integer is considered
+		// corrupt.
+		//
+		// If we need bigger integers in future, old versions liblzma
+		// will confusingly indicate the file being corrupt istead of
+		// unsupported. I suppose it's still better this way, because
+		// in the foreseeable future (writing this in 2008) the only
+		// reason why files would appear having over 63-bit integers
+		// is that the files are simply corrupt.
+		if (*vli_pos == LZMA_VLI_BYTES_MAX)
+			return LZMA_DATA_ERROR;
+
+	} while (*in_pos < in_size);
+
+	return vli_pos == &vli_pos_internal ? LZMA_DATA_ERROR : LZMA_OK;
+}
diff --git a/Utilities/cmliblzma/liblzma/common/vli_encoder.c b/Utilities/cmliblzma/liblzma/common/vli_encoder.c
new file mode 100644
index 0000000..09e90cb
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/vli_encoder.c
@@ -0,0 +1,69 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       vli_encoder.c
+/// \brief      Encodes variable-length integers
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "common.h"
+
+
+extern LZMA_API(lzma_ret)
+lzma_vli_encode(lzma_vli vli, size_t *vli_pos,
+		uint8_t *LZMA_RESTRICT out, size_t *LZMA_RESTRICT out_pos,
+		size_t out_size)
+{
+	// If we haven't been given vli_pos, work in single-call mode.
+	size_t vli_pos_internal = 0;
+	if (vli_pos == NULL) {
+		vli_pos = &vli_pos_internal;
+
+		// In single-call mode, we expect that the caller has
+		// reserved enough output space.
+		if (*out_pos >= out_size)
+			return LZMA_PROG_ERROR;
+	} else {
+		// This never happens when we are called by liblzma, but
+		// may happen if called directly from an application.
+		if (*out_pos >= out_size)
+			return LZMA_BUF_ERROR;
+	}
+
+	// Validate the arguments.
+	if (*vli_pos >= LZMA_VLI_BYTES_MAX || vli > LZMA_VLI_MAX)
+		return LZMA_PROG_ERROR;
+
+	// Shift vli so that the next bits to encode are the lowest. In
+	// single-call mode this never changes vli since *vli_pos is zero.
+	vli >>= *vli_pos * 7;
+
+	// Write the non-last bytes in a loop.
+	while (vli >= 0x80) {
+		// We don't need *vli_pos during this function call anymore,
+		// but update it here so that it is ready if we need to
+		// return before the whole integer has been decoded.
+		++*vli_pos;
+		assert(*vli_pos < LZMA_VLI_BYTES_MAX);
+
+		// Write the next byte.
+		out[*out_pos] = (uint8_t)(vli) | 0x80;
+		vli >>= 7;
+
+		if (++*out_pos == out_size)
+			return vli_pos == &vli_pos_internal
+					? LZMA_PROG_ERROR : LZMA_OK;
+	}
+
+	// Write the last byte.
+	out[*out_pos] = (uint8_t)(vli);
+	++*out_pos;
+	++*vli_pos;
+
+	return vli_pos == &vli_pos_internal ? LZMA_OK : LZMA_STREAM_END;
+
+}
diff --git a/Utilities/cmliblzma/liblzma/common/vli_size.c b/Utilities/cmliblzma/liblzma/common/vli_size.c
new file mode 100644
index 0000000..8b931e4
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/vli_size.c
@@ -0,0 +1,31 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       vli_size.c
+/// \brief      Calculates the encoded size of a variable-length integer
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "common.h"
+
+
+extern LZMA_API(uint32_t)
+lzma_vli_size(lzma_vli vli)
+{
+	uint32_t i = 0;
+
+	if (vli > LZMA_VLI_MAX)
+		return 0;
+
+	do {
+		vli >>= 7;
+		++i;
+	} while (vli != 0);
+
+	assert(i <= LZMA_VLI_BYTES_MAX);
+	return i;
+}
diff --git a/Utilities/cmliblzma/liblzma/delta/delta_common.c b/Utilities/cmliblzma/liblzma/delta/delta_common.c
new file mode 100644
index 0000000..803e674
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/delta/delta_common.c
@@ -0,0 +1,72 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       delta_common.c
+/// \brief      Common stuff for Delta encoder and decoder
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "delta_common.h"
+#include "delta_private.h"
+
+
+static void
+delta_coder_end(lzma_coder *coder, lzma_allocator *allocator)
+{
+	lzma_next_end(&coder->next, allocator);
+	lzma_free(coder, allocator);
+	return;
+}
+
+
+extern lzma_ret
+lzma_delta_coder_init(lzma_next_coder *next, lzma_allocator *allocator,
+		const lzma_filter_info *filters)
+{
+	const lzma_options_delta *opt;
+
+	// Allocate memory for the decoder if needed.
+	if (next->coder == NULL) {
+		next->coder = lzma_alloc(sizeof(lzma_coder), allocator);
+		if (next->coder == NULL)
+			return LZMA_MEM_ERROR;
+
+		// End function is the same for encoder and decoder.
+		next->end = &delta_coder_end;
+		next->coder->next = LZMA_NEXT_CODER_INIT;
+	}
+
+	// Validate the options.
+	if (lzma_delta_coder_memusage(filters[0].options) == UINT64_MAX)
+		return LZMA_OPTIONS_ERROR;
+
+	// Set the delta distance.
+	opt = filters[0].options;
+	next->coder->distance = opt->dist;
+
+	// Initialize the rest of the variables.
+	next->coder->pos = 0;
+	memzero(next->coder->history, LZMA_DELTA_DIST_MAX);
+
+	// Initialize the next decoder in the chain, if any.
+	return lzma_next_filter_init(&next->coder->next,
+			allocator, filters + 1);
+}
+
+
+extern uint64_t
+lzma_delta_coder_memusage(const void *options)
+{
+	const lzma_options_delta *opt = options;
+
+	if (opt == NULL || opt->type != LZMA_DELTA_TYPE_BYTE
+			|| opt->dist < LZMA_DELTA_DIST_MIN
+			|| opt->dist > LZMA_DELTA_DIST_MAX)
+		return UINT64_MAX;
+
+	return sizeof(lzma_coder);
+}
diff --git a/Utilities/cmliblzma/liblzma/delta/delta_common.h b/Utilities/cmliblzma/liblzma/delta/delta_common.h
new file mode 100644
index 0000000..7e7e1ba
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/delta/delta_common.h
@@ -0,0 +1,20 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       delta_common.h
+/// \brief      Common stuff for Delta encoder and decoder
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#ifndef LZMA_DELTA_COMMON_H
+#define LZMA_DELTA_COMMON_H
+
+#include "common.h"
+
+extern uint64_t lzma_delta_coder_memusage(const void *options);
+
+#endif
diff --git a/Utilities/cmliblzma/liblzma/delta/delta_decoder.c b/Utilities/cmliblzma/liblzma/delta/delta_decoder.c
new file mode 100644
index 0000000..28df727
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/delta/delta_decoder.c
@@ -0,0 +1,79 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       delta_decoder.c
+/// \brief      Delta filter decoder
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "delta_decoder.h"
+#include "delta_private.h"
+
+
+static void
+decode_buffer(lzma_coder *coder, uint8_t *buffer, size_t size)
+{
+	size_t i;
+	const size_t distance = coder->distance;
+
+	for (i = 0; i < size; ++i) {
+		buffer[i] += coder->history[(distance + coder->pos) & 0xFF];
+		coder->history[coder->pos-- & 0xFF] = buffer[i];
+	}
+}
+
+
+static lzma_ret
+delta_decode(lzma_coder *coder, lzma_allocator *allocator,
+		const uint8_t *LZMA_RESTRICT in, size_t *LZMA_RESTRICT in_pos,
+		size_t in_size, uint8_t *LZMA_RESTRICT out,
+		size_t *LZMA_RESTRICT out_pos, size_t out_size, lzma_action action)
+{
+	const size_t out_start = *out_pos;
+	lzma_ret ret;
+
+	assert(coder->next.code != NULL);
+
+	ret = coder->next.code(coder->next.coder, allocator,
+			in, in_pos, in_size, out, out_pos, out_size,
+			action);
+
+	decode_buffer(coder, out + out_start, *out_pos - out_start);
+
+	return ret;
+}
+
+
+extern lzma_ret
+lzma_delta_decoder_init(lzma_next_coder *next, lzma_allocator *allocator,
+		const lzma_filter_info *filters)
+{
+	next->code = &delta_decode;
+	return lzma_delta_coder_init(next, allocator, filters);
+}
+
+
+extern lzma_ret
+lzma_delta_props_decode(void **options, lzma_allocator *allocator,
+		const uint8_t *props, size_t props_size)
+{
+	lzma_options_delta *opt;
+
+	if (props_size != 1)
+		return LZMA_OPTIONS_ERROR;
+
+	opt = lzma_alloc(sizeof(lzma_options_delta), allocator);
+	if (opt == NULL)
+		return LZMA_MEM_ERROR;
+
+	opt->type = LZMA_DELTA_TYPE_BYTE;
+	opt->dist = props[0] + 1;
+
+	*options = opt;
+
+	return LZMA_OK;
+}
diff --git a/Utilities/cmliblzma/liblzma/delta/delta_decoder.h b/Utilities/cmliblzma/liblzma/delta/delta_decoder.h
new file mode 100644
index 0000000..ae89acc
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/delta/delta_decoder.h
@@ -0,0 +1,25 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       delta_decoder.h
+/// \brief      Delta filter decoder
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#ifndef LZMA_DELTA_DECODER_H
+#define LZMA_DELTA_DECODER_H
+
+#include "delta_common.h"
+
+extern lzma_ret lzma_delta_decoder_init(lzma_next_coder *next,
+		lzma_allocator *allocator, const lzma_filter_info *filters);
+
+extern lzma_ret lzma_delta_props_decode(
+		void **options, lzma_allocator *allocator,
+		const uint8_t *props, size_t props_size);
+
+#endif
diff --git a/Utilities/cmliblzma/liblzma/delta/delta_encoder.c b/Utilities/cmliblzma/liblzma/delta/delta_encoder.c
new file mode 100644
index 0000000..a39c154
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/delta/delta_encoder.c
@@ -0,0 +1,124 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       delta_encoder.c
+/// \brief      Delta filter encoder
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "delta_encoder.h"
+#include "delta_private.h"
+
+
+/// Copies and encodes the data at the same time. This is used when Delta
+/// is the first filter in the chain (and thus the last filter in the
+/// encoder's filter stack).
+static void
+copy_and_encode(lzma_coder *coder,
+		const uint8_t *LZMA_RESTRICT in, uint8_t *LZMA_RESTRICT out, size_t size)
+{
+	size_t i;
+	const size_t distance = coder->distance;
+
+	for (i = 0; i < size; ++i) {
+		const uint8_t tmp = coder->history[
+				(distance + coder->pos) & 0xFF];
+		coder->history[coder->pos-- & 0xFF] = in[i];
+		out[i] = in[i] - tmp;
+	}
+}
+
+
+/// Encodes the data in place. This is used when we are the last filter
+/// in the chain (and thus non-last filter in the encoder's filter stack).
+static void
+encode_in_place(lzma_coder *coder, uint8_t *buffer, size_t size)
+{
+	size_t i;
+	const size_t distance = coder->distance;
+
+	for (i = 0; i < size; ++i) {
+		const uint8_t tmp = coder->history[
+				(distance + coder->pos) & 0xFF];
+		coder->history[coder->pos-- & 0xFF] = buffer[i];
+		buffer[i] -= tmp;
+	}
+}
+
+
+static lzma_ret
+delta_encode(lzma_coder *coder, lzma_allocator *allocator,
+		const uint8_t *LZMA_RESTRICT in, size_t *LZMA_RESTRICT in_pos,
+		size_t in_size, uint8_t *LZMA_RESTRICT out,
+		size_t *LZMA_RESTRICT out_pos, size_t out_size, lzma_action action)
+{
+	lzma_ret ret;
+
+	if (coder->next.code == NULL) {
+		const size_t in_avail = in_size - *in_pos;
+		const size_t out_avail = out_size - *out_pos;
+		const size_t size = my_min(in_avail, out_avail);
+
+		copy_and_encode(coder, in + *in_pos, out + *out_pos, size);
+
+		*in_pos += size;
+		*out_pos += size;
+
+		ret = action != LZMA_RUN && *in_pos == in_size
+				? LZMA_STREAM_END : LZMA_OK;
+
+	} else {
+		const size_t out_start = *out_pos;
+
+		ret = coder->next.code(coder->next.coder, allocator,
+				in, in_pos, in_size, out, out_pos, out_size,
+				action);
+
+		encode_in_place(coder, out + out_start, *out_pos - out_start);
+	}
+
+	return ret;
+}
+
+
+static lzma_ret
+delta_encoder_update(lzma_coder *coder, lzma_allocator *allocator,
+		const lzma_filter *filters_null lzma_attribute((__unused__)),
+		const lzma_filter *reversed_filters)
+{
+	// Delta doesn't and will never support changing the options in
+	// the middle of encoding. If the app tries to change them, we
+	// simply ignore them.
+	return lzma_next_filter_update(
+			&coder->next, allocator, reversed_filters + 1);
+}
+
+
+extern lzma_ret
+lzma_delta_encoder_init(lzma_next_coder *next, lzma_allocator *allocator,
+		const lzma_filter_info *filters)
+{
+	next->code = &delta_encode;
+	next->update = &delta_encoder_update;
+	return lzma_delta_coder_init(next, allocator, filters);
+}
+
+
+extern lzma_ret
+lzma_delta_props_encode(const void *options, uint8_t *out)
+{
+	const lzma_options_delta *opt = options;
+
+	// The caller must have already validated the options, so it's
+	// LZMA_PROG_ERROR if they are invalid.
+	if (lzma_delta_coder_memusage(options) == UINT64_MAX)
+		return LZMA_PROG_ERROR;
+
+	out[0] = opt->dist - LZMA_DELTA_DIST_MIN;
+
+	return LZMA_OK;
+}
diff --git a/Utilities/cmliblzma/liblzma/delta/delta_encoder.h b/Utilities/cmliblzma/liblzma/delta/delta_encoder.h
new file mode 100644
index 0000000..a447862
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/delta/delta_encoder.h
@@ -0,0 +1,23 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       delta_encoder.h
+/// \brief      Delta filter encoder
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#ifndef LZMA_DELTA_ENCODER_H
+#define LZMA_DELTA_ENCODER_H
+
+#include "delta_common.h"
+
+extern lzma_ret lzma_delta_encoder_init(lzma_next_coder *next,
+		lzma_allocator *allocator, const lzma_filter_info *filters);
+
+extern lzma_ret lzma_delta_props_encode(const void *options, uint8_t *out);
+
+#endif
diff --git a/Utilities/cmliblzma/liblzma/delta/delta_private.h b/Utilities/cmliblzma/liblzma/delta/delta_private.h
new file mode 100644
index 0000000..62b7fed
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/delta/delta_private.h
@@ -0,0 +1,37 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       delta_private.h
+/// \brief      Private common stuff for Delta encoder and decoder
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#ifndef LZMA_DELTA_PRIVATE_H
+#define LZMA_DELTA_PRIVATE_H
+
+#include "delta_common.h"
+
+struct lzma_coder_s {
+	/// Next coder in the chain
+	lzma_next_coder next;
+
+	/// Delta distance
+	size_t distance;
+
+	/// Position in history[]
+	uint8_t pos;
+
+	/// Buffer to hold history of the original data
+	uint8_t history[LZMA_DELTA_DIST_MAX];
+};
+
+
+extern lzma_ret lzma_delta_coder_init(
+		lzma_next_coder *next, lzma_allocator *allocator,
+		const lzma_filter_info *filters);
+
+#endif
diff --git a/Utilities/cmliblzma/liblzma/liblzma.pc.in b/Utilities/cmliblzma/liblzma/liblzma.pc.in
new file mode 100644
index 0000000..7f11f1a
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/liblzma.pc.in
@@ -0,0 +1,19 @@
+#
+# Author: Lasse Collin
+#
+# This file has been put into the public domain.
+# You can do whatever you want with this file.
+#
+
+prefix=@prefix@
+exec_prefix=@exec_prefix@
+libdir=@libdir@
+includedir=@includedir@
+
+Name: liblzma
+Description: General purpose data compression library
+URL: @PACKAGE_URL@
+Version: @PACKAGE_VERSION@
+Cflags: -I${includedir}
+Libs: -L${libdir} -llzma
+Libs.private: @PTHREAD_CFLAGS@ @PTHREAD_LIBS@
diff --git a/Utilities/cmliblzma/liblzma/liblzma_w32res.rc b/Utilities/cmliblzma/liblzma/liblzma_w32res.rc
new file mode 100644
index 0000000..773caf8
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/liblzma_w32res.rc
@@ -0,0 +1,14 @@
+/*
+ * Author: Lasse Collin
+ *
+ * This file has been put into the public domain.
+ * You can do whatever you want with this file.
+ */
+
+#define MY_TYPE VFT_DLL
+#define MY_NAME "liblzma"
+#define MY_SUFFIX ".dll"
+#define MY_DESC "liblzma data compression library"
+#define PACKAGE_NAME "XZ Utils"
+#define PACKAGE_URL "http://tukaani.org/xz/"
+#include "common_w32res.rc"
diff --git a/Utilities/cmliblzma/liblzma/lz/lz_decoder.c b/Utilities/cmliblzma/liblzma/lz/lz_decoder.c
new file mode 100644
index 0000000..9fa1bdc
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/lz/lz_decoder.c
@@ -0,0 +1,307 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       lz_decoder.c
+/// \brief      LZ out window
+///
+//  Authors:    Igor Pavlov
+//              Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+// liblzma supports multiple LZ77-based filters. The LZ part is shared
+// between these filters. The LZ code takes care of dictionary handling
+// and passing the data between filters in the chain. The filter-specific
+// part decodes from the input buffer to the dictionary.
+
+
+#include "lz_decoder.h"
+
+
+struct lzma_coder_s {
+	/// Dictionary (history buffer)
+	lzma_dict dict;
+
+	/// The actual LZ-based decoder e.g. LZMA
+	lzma_lz_decoder lz;
+
+	/// Next filter in the chain, if any. Note that LZMA and LZMA2 are
+	/// only allowed as the last filter, but the long-range filter in
+	/// future can be in the middle of the chain.
+	lzma_next_coder next;
+
+	/// True if the next filter in the chain has returned LZMA_STREAM_END.
+	bool next_finished;
+
+	/// True if the LZ decoder (e.g. LZMA) has detected end of payload
+	/// marker. This may become true before next_finished becomes true.
+	bool this_finished;
+
+	/// Temporary buffer needed when the LZ-based filter is not the last
+	/// filter in the chain. The output of the next filter is first
+	/// decoded into buffer[], which is then used as input for the actual
+	/// LZ-based decoder.
+	struct {
+		size_t pos;
+		size_t size;
+		uint8_t buffer[LZMA_BUFFER_SIZE];
+	} temp;
+};
+
+
+static void
+lz_decoder_reset(lzma_coder *coder)
+{
+	coder->dict.pos = 0;
+	coder->dict.full = 0;
+	coder->dict.buf[coder->dict.size - 1] = '\0';
+	coder->dict.need_reset = false;
+	return;
+}
+
+
+static lzma_ret
+decode_buffer(lzma_coder *coder,
+		const uint8_t *LZMA_RESTRICT in, size_t *LZMA_RESTRICT in_pos,
+		size_t in_size, uint8_t *LZMA_RESTRICT out,
+		size_t *LZMA_RESTRICT out_pos, size_t out_size)
+{
+	while (true) {
+		size_t copy_size;
+		size_t dict_start;
+		lzma_ret ret;
+
+		// Wrap the dictionary if needed.
+		if (coder->dict.pos == coder->dict.size)
+			coder->dict.pos = 0;
+
+		// Store the current dictionary position. It is needed to know
+		// where to start copying to the out[] buffer.
+		dict_start = coder->dict.pos;
+
+		// Calculate how much we allow coder->lz.code() to decode.
+		// It must not decode past the end of the dictionary
+		// buffer, and we don't want it to decode more than is
+		// actually needed to fill the out[] buffer.
+		coder->dict.limit = coder->dict.pos
+				+ my_min(out_size - *out_pos,
+					coder->dict.size - coder->dict.pos);
+
+		// Call the coder->lz.code() to do the actual decoding.
+		ret = coder->lz.code(
+				coder->lz.coder, &coder->dict,
+				in, in_pos, in_size);
+
+		// Copy the decoded data from the dictionary to the out[]
+		// buffer.
+		copy_size = coder->dict.pos - dict_start;
+		assert(copy_size <= out_size - *out_pos);
+		memcpy(out + *out_pos, coder->dict.buf + dict_start,
+				copy_size);
+		*out_pos += copy_size;
+
+		// Reset the dictionary if so requested by coder->lz.code().
+		if (coder->dict.need_reset) {
+			lz_decoder_reset(coder);
+
+			// Since we reset dictionary, we don't check if
+			// dictionary became full.
+			if (ret != LZMA_OK || *out_pos == out_size)
+				return ret;
+		} else {
+			// Return if everything got decoded or an error
+			// occurred, or if there's no more data to decode.
+			//
+			// Note that detecting if there's something to decode
+			// is done by looking if dictionary become full
+			// instead of looking if *in_pos == in_size. This
+			// is because it is possible that all the input was
+			// consumed already but some data is pending to be
+			// written to the dictionary.
+			if (ret != LZMA_OK || *out_pos == out_size
+					|| coder->dict.pos < coder->dict.size)
+				return ret;
+		}
+	}
+}
+
+
+static lzma_ret
+lz_decode(lzma_coder *coder,
+		lzma_allocator *allocator lzma_attribute((__unused__)),
+		const uint8_t *LZMA_RESTRICT in, size_t *LZMA_RESTRICT in_pos,
+		size_t in_size, uint8_t *LZMA_RESTRICT out,
+		size_t *LZMA_RESTRICT out_pos, size_t out_size,
+		lzma_action action)
+{
+	if (coder->next.code == NULL)
+		return decode_buffer(coder, in, in_pos, in_size,
+				out, out_pos, out_size);
+
+	// We aren't the last coder in the chain, we need to decode
+	// our input to a temporary buffer.
+	while (*out_pos < out_size) {
+		lzma_ret ret;
+
+		// Fill the temporary buffer if it is empty.
+		if (!coder->next_finished
+				&& coder->temp.pos == coder->temp.size) {
+			coder->temp.pos = 0;
+			coder->temp.size = 0;
+
+			ret = coder->next.code(
+					coder->next.coder,
+					allocator, in, in_pos, in_size,
+					coder->temp.buffer, &coder->temp.size,
+					LZMA_BUFFER_SIZE, action);
+
+			if (ret == LZMA_STREAM_END)
+				coder->next_finished = true;
+			else if (ret != LZMA_OK || coder->temp.size == 0)
+				return ret;
+		}
+
+		if (coder->this_finished) {
+			if (coder->temp.size != 0)
+				return LZMA_DATA_ERROR;
+
+			if (coder->next_finished)
+				return LZMA_STREAM_END;
+
+			return LZMA_OK;
+		}
+
+		ret = decode_buffer(coder, coder->temp.buffer,
+				&coder->temp.pos, coder->temp.size,
+				out, out_pos, out_size);
+
+		if (ret == LZMA_STREAM_END)
+			coder->this_finished = true;
+		else if (ret != LZMA_OK)
+			return ret;
+		else if (coder->next_finished && *out_pos < out_size)
+			return LZMA_DATA_ERROR;
+	}
+
+	return LZMA_OK;
+}
+
+
+static void
+lz_decoder_end(lzma_coder *coder, lzma_allocator *allocator)
+{
+	lzma_next_end(&coder->next, allocator);
+	lzma_free(coder->dict.buf, allocator);
+
+	if (coder->lz.end != NULL)
+		coder->lz.end(coder->lz.coder, allocator);
+	else
+		lzma_free(coder->lz.coder, allocator);
+
+	lzma_free(coder, allocator);
+	return;
+}
+
+
+extern lzma_ret
+lzma_lz_decoder_init(lzma_next_coder *next, lzma_allocator *allocator,
+		const lzma_filter_info *filters,
+		lzma_ret (*lz_init)(lzma_lz_decoder *lz,
+			lzma_allocator *allocator, const void *options,
+			lzma_lz_options *lz_options))
+{
+	lzma_lz_options lz_options;
+
+	// Allocate the base structure if it isn't already allocated.
+	if (next->coder == NULL) {
+		next->coder = lzma_alloc(sizeof(lzma_coder), allocator);
+		if (next->coder == NULL)
+			return LZMA_MEM_ERROR;
+
+		next->code = &lz_decode;
+		next->end = &lz_decoder_end;
+
+		next->coder->dict.buf = NULL;
+		next->coder->dict.size = 0;
+		next->coder->lz = LZMA_LZ_DECODER_INIT;
+		next->coder->next = LZMA_NEXT_CODER_INIT;
+	}
+
+	// Allocate and initialize the LZ-based decoder. It will also give
+	// us the dictionary size.
+	return_if_error(lz_init(&next->coder->lz, allocator,
+			filters[0].options, &lz_options));
+
+	// If the dictionary size is very small, increase it to 4096 bytes.
+	// This is to prevent constant wrapping of the dictionary, which
+	// would slow things down. The downside is that since we don't check
+	// separately for the real dictionary size, we may happily accept
+	// corrupt files.
+	if (lz_options.dict_size < 4096)
+		lz_options.dict_size = 4096;
+
+	// Make dictionary size a multipe of 16. Some LZ-based decoders like
+	// LZMA use the lowest bits lzma_dict.pos to know the alignment of the
+	// data. Aligned buffer is also good when memcpying from the
+	// dictionary to the output buffer, since applications are
+	// recommended to give aligned buffers to liblzma.
+	//
+	// Avoid integer overflow.
+	if (lz_options.dict_size > SIZE_MAX - 15)
+		return LZMA_MEM_ERROR;
+
+	lz_options.dict_size = (lz_options.dict_size + 15) & ~((size_t)(15));
+
+	// Allocate and initialize the dictionary.
+	if (next->coder->dict.size != lz_options.dict_size) {
+		lzma_free(next->coder->dict.buf, allocator);
+		next->coder->dict.buf
+				= lzma_alloc(lz_options.dict_size, allocator);
+		if (next->coder->dict.buf == NULL)
+			return LZMA_MEM_ERROR;
+
+		next->coder->dict.size = lz_options.dict_size;
+	}
+
+	lz_decoder_reset(next->coder);
+
+	// Use the preset dictionary if it was given to us.
+	if (lz_options.preset_dict != NULL
+			&& lz_options.preset_dict_size > 0) {
+		// If the preset dictionary is bigger than the actual
+		// dictionary, copy only the tail.
+		const size_t copy_size = my_min(lz_options.preset_dict_size,
+				lz_options.dict_size);
+		const size_t offset = lz_options.preset_dict_size - copy_size;
+		memcpy(next->coder->dict.buf, lz_options.preset_dict + offset,
+				copy_size);
+		next->coder->dict.pos = copy_size;
+		next->coder->dict.full = copy_size;
+	}
+
+	// Miscellaneous initializations
+	next->coder->next_finished = false;
+	next->coder->this_finished = false;
+	next->coder->temp.pos = 0;
+	next->coder->temp.size = 0;
+
+	// Initialize the next filter in the chain, if any.
+	return lzma_next_filter_init(&next->coder->next, allocator,
+			filters + 1);
+}
+
+
+extern uint64_t
+lzma_lz_decoder_memusage(size_t dictionary_size)
+{
+	return sizeof(lzma_coder) + (uint64_t)(dictionary_size);
+}
+
+
+extern void
+lzma_lz_decoder_uncompressed(lzma_coder *coder, lzma_vli uncompressed_size)
+{
+	coder->lz.set_uncompressed(coder->lz.coder, uncompressed_size);
+}
diff --git a/Utilities/cmliblzma/liblzma/lz/lz_decoder.h b/Utilities/cmliblzma/liblzma/lz/lz_decoder.h
new file mode 100644
index 0000000..76011f2
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/lz/lz_decoder.h
@@ -0,0 +1,236 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       lz_decoder.h
+/// \brief      LZ out window
+///
+//  Authors:    Igor Pavlov
+//              Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#ifndef LZMA_LZ_DECODER_H
+#define LZMA_LZ_DECODER_H
+
+#include "common.h"
+
+
+typedef struct {
+	/// Pointer to the dictionary buffer. It can be an allocated buffer
+	/// internal to liblzma, or it can a be a buffer given by the
+	/// application when in single-call mode (not implemented yet).
+	uint8_t *buf;
+
+	/// Write position in dictionary. The next byte will be written to
+	/// buf[pos].
+	size_t pos;
+
+	/// Indicates how full the dictionary is. This is used by
+	/// dict_is_distance_valid() to detect corrupt files that would
+	/// read beyond the beginning of the dictionary.
+	size_t full;
+
+	/// Write limit
+	size_t limit;
+
+	/// Size of the dictionary
+	size_t size;
+
+	/// True when dictionary should be reset before decoding more data.
+	bool need_reset;
+
+} lzma_dict;
+
+
+typedef struct {
+	size_t dict_size;
+	const uint8_t *preset_dict;
+	size_t preset_dict_size;
+} lzma_lz_options;
+
+
+typedef struct {
+	/// Data specific to the LZ-based decoder
+	lzma_coder *coder;
+
+	/// Function to decode from in[] to *dict
+	lzma_ret (*code)(lzma_coder *LZMA_RESTRICT coder,
+			lzma_dict *LZMA_RESTRICT dict, const uint8_t *LZMA_RESTRICT in,
+			size_t *LZMA_RESTRICT in_pos, size_t in_size);
+
+	void (*reset)(lzma_coder *coder, const void *options);
+
+	/// Set the uncompressed size
+	void (*set_uncompressed)(lzma_coder *coder,
+			lzma_vli uncompressed_size);
+
+	/// Free allocated resources
+	void (*end)(lzma_coder *coder, lzma_allocator *allocator);
+
+} lzma_lz_decoder;
+
+
+static const lzma_lz_decoder LZMA_LZ_DECODER_INIT =
+	{
+		NULL,
+		NULL,
+		NULL,
+		NULL,
+		NULL,
+	};
+
+
+extern lzma_ret lzma_lz_decoder_init(lzma_next_coder *next,
+		lzma_allocator *allocator, const lzma_filter_info *filters,
+		lzma_ret (*lz_init)(lzma_lz_decoder *lz,
+			lzma_allocator *allocator, const void *options,
+			lzma_lz_options *lz_options));
+
+extern uint64_t lzma_lz_decoder_memusage(size_t dictionary_size);
+
+extern void lzma_lz_decoder_uncompressed(
+		lzma_coder *coder, lzma_vli uncompressed_size);
+
+
+//////////////////////
+// Inline functions //
+//////////////////////
+
+/// Get a byte from the history buffer.
+static inline uint8_t
+dict_get(const lzma_dict *const dict, const uint32_t distance)
+{
+	return dict->buf[dict->pos - distance - 1
+			+ (distance < dict->pos ? 0 : dict->size)];
+}
+
+
+/// Test if dictionary is empty.
+static inline bool
+dict_is_empty(const lzma_dict *const dict)
+{
+	return dict->full == 0;
+}
+
+
+/// Validate the match distance
+static inline bool
+dict_is_distance_valid(const lzma_dict *const dict, const size_t distance)
+{
+	return dict->full > distance;
+}
+
+
+/// Repeat *len bytes at distance.
+static inline bool
+dict_repeat(lzma_dict *dict, uint32_t distance, uint32_t *len)
+{
+	// Don't write past the end of the dictionary.
+	const size_t dict_avail = dict->limit - dict->pos;
+	uint32_t left = my_min(dict_avail, *len);
+	*len -= left;
+
+	// Repeat a block of data from the history. Because memcpy() is faster
+	// than copying byte by byte in a loop, the copying process gets split
+	// into three cases.
+	if (distance < left) {
+		// Source and target areas overlap, thus we can't use
+		// memcpy() nor even memmove() safely.
+		do {
+			dict->buf[dict->pos] = dict_get(dict, distance);
+			++dict->pos;
+		} while (--left > 0);
+
+	} else if (distance < dict->pos) {
+		// The easiest and fastest case
+		memcpy(dict->buf + dict->pos,
+				dict->buf + dict->pos - distance - 1,
+				left);
+		dict->pos += left;
+
+	} else {
+		uint32_t copy_pos;
+		uint32_t copy_size;
+
+		// The bigger the dictionary, the more rare this
+		// case occurs. We need to "wrap" the dict, thus
+		// we might need two memcpy() to copy all the data.
+		assert(dict->full == dict->size);
+		copy_pos = dict->pos - distance - 1 + dict->size;
+		copy_size = dict->size - copy_pos;
+
+		if (copy_size < left) {
+			memmove(dict->buf + dict->pos, dict->buf + copy_pos,
+					copy_size);
+			dict->pos += copy_size;
+			copy_size = left - copy_size;
+			memcpy(dict->buf + dict->pos, dict->buf, copy_size);
+			dict->pos += copy_size;
+		} else {
+			memmove(dict->buf + dict->pos, dict->buf + copy_pos,
+					left);
+			dict->pos += left;
+		}
+	}
+
+	// Update how full the dictionary is.
+	if (dict->full < dict->pos)
+		dict->full = dict->pos;
+
+	return unlikely(*len != 0);
+}
+
+
+/// Puts one byte into the dictionary. Returns true if the dictionary was
+/// already full and the byte couldn't be added.
+static inline bool
+dict_put(lzma_dict *dict, uint8_t byte)
+{
+	if (unlikely(dict->pos == dict->limit))
+		return true;
+
+	dict->buf[dict->pos++] = byte;
+
+	if (dict->pos > dict->full)
+		dict->full = dict->pos;
+
+	return false;
+}
+
+
+/// Copies arbitrary amount of data into the dictionary.
+static inline void
+dict_write(lzma_dict *LZMA_RESTRICT dict, const uint8_t *LZMA_RESTRICT in,
+		size_t *LZMA_RESTRICT in_pos, size_t in_size,
+		size_t *LZMA_RESTRICT left)
+{
+	// NOTE: If we are being given more data than the size of the
+	// dictionary, it could be possible to optimize the LZ decoder
+	// so that not everything needs to go through the dictionary.
+	// This shouldn't be very common thing in practice though, and
+	// the slowdown of one extra memcpy() isn't bad compared to how
+	// much time it would have taken if the data were compressed.
+
+	if (in_size - *in_pos > *left)
+		in_size = *in_pos + *left;
+
+	*left -= lzma_bufcpy(in, in_pos, in_size,
+			dict->buf, &dict->pos, dict->limit);
+
+	if (dict->pos > dict->full)
+		dict->full = dict->pos;
+
+	return;
+}
+
+
+static inline void
+dict_reset(lzma_dict *dict)
+{
+	dict->need_reset = true;
+	return;
+}
+
+#endif
diff --git a/Utilities/cmliblzma/liblzma/lz/lz_encoder.c b/Utilities/cmliblzma/liblzma/lz/lz_encoder.c
new file mode 100644
index 0000000..1dae924
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/lz/lz_encoder.c
@@ -0,0 +1,594 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       lz_encoder.c
+/// \brief      LZ in window
+///
+//  Authors:    Igor Pavlov
+//              Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "lz_encoder.h"
+#include "lz_encoder_hash.h"
+
+// See lz_encoder_hash.h. This is a bit hackish but avoids making
+// endianness a conditional in makefiles.
+#if defined(WORDS_BIGENDIAN) && !defined(HAVE_SMALL)
+#	include "lz_encoder_hash_table.h"
+#endif
+
+
+struct lzma_coder_s {
+	/// LZ-based encoder e.g. LZMA
+	lzma_lz_encoder lz;
+
+	/// History buffer and match finder
+	lzma_mf mf;
+
+	/// Next coder in the chain
+	lzma_next_coder next;
+};
+
+
+/// \brief      Moves the data in the input window to free space for new data
+///
+/// mf->buffer is a sliding input window, which keeps mf->keep_size_before
+/// bytes of input history available all the time. Now and then we need to
+/// "slide" the buffer to make space for the new data to the end of the
+/// buffer. At the same time, data older than keep_size_before is dropped.
+///
+static void
+move_window(lzma_mf *mf)
+{
+	uint32_t move_offset;
+	size_t move_size;
+
+	// Align the move to a multiple of 16 bytes. Some LZ-based encoders
+	// like LZMA use the lowest bits of mf->read_pos to know the
+	// alignment of the uncompressed data. We also get better speed
+	// for memmove() with aligned buffers.
+	assert(mf->read_pos > mf->keep_size_before);
+	move_offset = (mf->read_pos - mf->keep_size_before) & ~UINT32_C(15);
+
+	assert(mf->write_pos > move_offset);
+	move_size = mf->write_pos - move_offset;
+
+	assert(move_offset + move_size <= mf->size);
+
+	memmove(mf->buffer, mf->buffer + move_offset, move_size);
+
+	mf->offset += move_offset;
+	mf->read_pos -= move_offset;
+	mf->read_limit -= move_offset;
+	mf->write_pos -= move_offset;
+
+	return;
+}
+
+
+/// \brief      Tries to fill the input window (mf->buffer)
+///
+/// If we are the last encoder in the chain, our input data is in in[].
+/// Otherwise we call the next filter in the chain to process in[] and
+/// write its output to mf->buffer.
+///
+/// This function must not be called once it has returned LZMA_STREAM_END.
+///
+static lzma_ret
+fill_window(lzma_coder *coder, lzma_allocator *allocator, const uint8_t *in,
+		size_t *in_pos, size_t in_size, lzma_action action)
+{
+	size_t write_pos;
+	lzma_ret ret;
+
+	assert(coder->mf.read_pos <= coder->mf.write_pos);
+
+	// Move the sliding window if needed.
+	if (coder->mf.read_pos >= coder->mf.size - coder->mf.keep_size_after)
+		move_window(&coder->mf);
+
+	// Maybe this is ugly, but lzma_mf uses uint32_t for most things
+	// (which I find cleanest), but we need size_t here when filling
+	// the history window.
+	write_pos = coder->mf.write_pos;
+	if (coder->next.code == NULL) {
+		// Not using a filter, simply memcpy() as much as possible.
+		lzma_bufcpy(in, in_pos, in_size, coder->mf.buffer,
+				&write_pos, coder->mf.size);
+
+		ret = action != LZMA_RUN && *in_pos == in_size
+				? LZMA_STREAM_END : LZMA_OK;
+
+	} else {
+		ret = coder->next.code(coder->next.coder, allocator,
+				in, in_pos, in_size,
+				coder->mf.buffer, &write_pos,
+				coder->mf.size, action);
+	}
+
+	coder->mf.write_pos = write_pos;
+
+	// If end of stream has been reached or flushing completed, we allow
+	// the encoder to process all the input (that is, read_pos is allowed
+	// to reach write_pos). Otherwise we keep keep_size_after bytes
+	// available as prebuffer.
+	if (ret == LZMA_STREAM_END) {
+		assert(*in_pos == in_size);
+		ret = LZMA_OK;
+		coder->mf.action = action;
+		coder->mf.read_limit = coder->mf.write_pos;
+
+	} else if (coder->mf.write_pos > coder->mf.keep_size_after) {
+		// This needs to be done conditionally, because if we got
+		// only little new input, there may be too little input
+		// to do any encoding yet.
+		coder->mf.read_limit = coder->mf.write_pos
+				- coder->mf.keep_size_after;
+	}
+
+	// Restart the match finder after finished LZMA_SYNC_FLUSH.
+	if (coder->mf.pending > 0
+			&& coder->mf.read_pos < coder->mf.read_limit) {
+		// Match finder may update coder->pending and expects it to
+		// start from zero, so use a temporary variable.
+		const size_t pending = coder->mf.pending;
+		coder->mf.pending = 0;
+
+		// Rewind read_pos so that the match finder can hash
+		// the pending bytes.
+		assert(coder->mf.read_pos >= pending);
+		coder->mf.read_pos -= pending;
+
+		// Call the skip function directly instead of using
+		// mf_skip(), since we don't want to touch mf->read_ahead.
+		coder->mf.skip(&coder->mf, pending);
+	}
+
+	return ret;
+}
+
+
+static lzma_ret
+lz_encode(lzma_coder *coder, lzma_allocator *allocator,
+		const uint8_t *LZMA_RESTRICT in, size_t *LZMA_RESTRICT in_pos,
+		size_t in_size,
+		uint8_t *LZMA_RESTRICT out, size_t *LZMA_RESTRICT out_pos,
+		size_t out_size, lzma_action action)
+{
+	while (*out_pos < out_size
+			&& (*in_pos < in_size || action != LZMA_RUN)) {
+		lzma_ret ret;
+
+		// Read more data to coder->mf.buffer if needed.
+		if (coder->mf.action == LZMA_RUN && coder->mf.read_pos
+				>= coder->mf.read_limit)
+			return_if_error(fill_window(coder, allocator,
+					in, in_pos, in_size, action));
+
+		// Encode
+		ret = coder->lz.code(coder->lz.coder,
+				&coder->mf, out, out_pos, out_size);
+		if (ret != LZMA_OK) {
+			// Setting this to LZMA_RUN for cases when we are
+			// flushing. It doesn't matter when finishing or if
+			// an error occurred.
+			coder->mf.action = LZMA_RUN;
+			return ret;
+		}
+	}
+
+	return LZMA_OK;
+}
+
+
+static bool
+lz_encoder_prepare(lzma_mf *mf, lzma_allocator *allocator,
+		const lzma_lz_options *lz_options)
+{
+	bool is_bt;
+	uint32_t new_count;
+	uint32_t reserve;
+	uint32_t old_size;
+	uint32_t hash_bytes;
+	uint32_t hs;
+	uint32_t old_count;
+
+	// For now, the dictionary size is limited to 1.5 GiB. This may grow
+	// in the future if needed, but it needs a little more work than just
+	// changing this check.
+	if (lz_options->dict_size < LZMA_DICT_SIZE_MIN
+			|| lz_options->dict_size
+				> (UINT32_C(1) << 30) + (UINT32_C(1) << 29)
+			|| lz_options->nice_len > lz_options->match_len_max)
+		return true;
+
+	mf->keep_size_before = lz_options->before_size + lz_options->dict_size;
+
+	mf->keep_size_after = lz_options->after_size
+			+ lz_options->match_len_max;
+
+	// To avoid constant memmove()s, allocate some extra space. Since
+	// memmove()s become more expensive when the size of the buffer
+	// increases, we reserve more space when a large dictionary is
+	// used to make the memmove() calls rarer.
+	//
+	// This works with dictionaries up to about 3 GiB. If bigger
+	// dictionary is wanted, some extra work is needed:
+	//   - Several variables in lzma_mf have to be changed from uint32_t
+	//     to size_t.
+	//   - Memory usage calculation needs something too, e.g. use uint64_t
+	//     for mf->size.
+	reserve = lz_options->dict_size / 2;
+	if (reserve > (UINT32_C(1) << 30))
+		reserve /= 2;
+
+	reserve += (lz_options->before_size + lz_options->match_len_max
+			+ lz_options->after_size) / 2 + (UINT32_C(1) << 19);
+
+	old_size = mf->size;
+	mf->size = mf->keep_size_before + reserve + mf->keep_size_after;
+
+	// Deallocate the old history buffer if it exists but has different
+	// size than what is needed now.
+	if (mf->buffer != NULL && old_size != mf->size) {
+		lzma_free(mf->buffer, allocator);
+		mf->buffer = NULL;
+	}
+
+	// Match finder options
+	mf->match_len_max = lz_options->match_len_max;
+	mf->nice_len = lz_options->nice_len;
+
+	// cyclic_size has to stay smaller than 2 Gi. Note that this doesn't
+	// mean limiting dictionary size to less than 2 GiB. With a match
+	// finder that uses multibyte resolution (hashes start at e.g. every
+	// fourth byte), cyclic_size would stay below 2 Gi even when
+	// dictionary size is greater than 2 GiB.
+	//
+	// It would be possible to allow cyclic_size >= 2 Gi, but then we
+	// would need to be careful to use 64-bit types in various places
+	// (size_t could do since we would need bigger than 32-bit address
+	// space anyway). It would also require either zeroing a multigigabyte
+	// buffer at initialization (waste of time and RAM) or allow
+	// normalization in lz_encoder_mf.c to access uninitialized
+	// memory to keep the code simpler. The current way is simple and
+	// still allows pretty big dictionaries, so I don't expect these
+	// limits to change.
+	mf->cyclic_size = lz_options->dict_size + 1;
+
+	// Validate the match finder ID and setup the function pointers.
+	switch (lz_options->match_finder) {
+#ifdef HAVE_MF_HC3
+	case LZMA_MF_HC3:
+		mf->find = &lzma_mf_hc3_find;
+		mf->skip = &lzma_mf_hc3_skip;
+		break;
+#endif
+#ifdef HAVE_MF_HC4
+	case LZMA_MF_HC4:
+		mf->find = &lzma_mf_hc4_find;
+		mf->skip = &lzma_mf_hc4_skip;
+		break;
+#endif
+#ifdef HAVE_MF_BT2
+	case LZMA_MF_BT2:
+		mf->find = &lzma_mf_bt2_find;
+		mf->skip = &lzma_mf_bt2_skip;
+		break;
+#endif
+#ifdef HAVE_MF_BT3
+	case LZMA_MF_BT3:
+		mf->find = &lzma_mf_bt3_find;
+		mf->skip = &lzma_mf_bt3_skip;
+		break;
+#endif
+#ifdef HAVE_MF_BT4
+	case LZMA_MF_BT4:
+		mf->find = &lzma_mf_bt4_find;
+		mf->skip = &lzma_mf_bt4_skip;
+		break;
+#endif
+
+	default:
+		return true;
+	}
+
+	// Calculate the sizes of mf->hash and mf->son and check that
+	// nice_len is big enough for the selected match finder.
+	hash_bytes = lz_options->match_finder & 0x0F;
+	if (hash_bytes > mf->nice_len)
+		return true;
+
+	is_bt = (lz_options->match_finder & 0x10) != 0;
+
+	if (hash_bytes == 2) {
+		hs = 0xFFFF;
+	} else {
+		// Round dictionary size up to the next 2^n - 1 so it can
+		// be used as a hash mask.
+		hs = lz_options->dict_size - 1;
+		hs |= hs >> 1;
+		hs |= hs >> 2;
+		hs |= hs >> 4;
+		hs |= hs >> 8;
+		hs >>= 1;
+		hs |= 0xFFFF;
+
+		if (hs > (UINT32_C(1) << 24)) {
+			if (hash_bytes == 3)
+				hs = (UINT32_C(1) << 24) - 1;
+			else
+				hs >>= 1;
+		}
+	}
+
+	mf->hash_mask = hs;
+
+	++hs;
+	if (hash_bytes > 2)
+		hs += HASH_2_SIZE;
+	if (hash_bytes > 3)
+		hs += HASH_3_SIZE;
+/*
+	No match finder uses this at the moment.
+	if (mf->hash_bytes > 4)
+		hs += HASH_4_SIZE;
+*/
+
+	// If the above code calculating hs is modified, make sure that
+	// this assertion stays valid (UINT32_MAX / 5 is not strictly the
+	// exact limit). If it doesn't, you need to calculate that
+	// hash_size_sum + sons_count cannot overflow.
+	assert(hs < UINT32_MAX / 5);
+
+	old_count = mf->hash_size_sum + mf->sons_count;
+	mf->hash_size_sum = hs;
+	mf->sons_count = mf->cyclic_size;
+	if (is_bt)
+		mf->sons_count *= 2;
+
+	new_count = mf->hash_size_sum + mf->sons_count;
+
+	// Deallocate the old hash array if it exists and has different size
+	// than what is needed now.
+	if (old_count != new_count) {
+		lzma_free(mf->hash, allocator);
+		mf->hash = NULL;
+	}
+
+	// Maximum number of match finder cycles
+	mf->depth = lz_options->depth;
+	if (mf->depth == 0) {
+		if (is_bt)
+			mf->depth = 16 + mf->nice_len / 2;
+		else
+			mf->depth = 4 + mf->nice_len / 4;
+	}
+
+	return false;
+}
+
+
+static bool
+lz_encoder_init(lzma_mf *mf, lzma_allocator *allocator,
+		const lzma_lz_options *lz_options)
+{
+	size_t alloc_count;
+
+	// Allocate the history buffer.
+	if (mf->buffer == NULL) {
+		mf->buffer = lzma_alloc(mf->size, allocator);
+		if (mf->buffer == NULL)
+			return true;
+	}
+
+	// Use cyclic_size as initial mf->offset. This allows
+	// avoiding a few branches in the match finders. The downside is
+	// that match finder needs to be normalized more often, which may
+	// hurt performance with huge dictionaries.
+	mf->offset = mf->cyclic_size;
+	mf->read_pos = 0;
+	mf->read_ahead = 0;
+	mf->read_limit = 0;
+	mf->write_pos = 0;
+	mf->pending = 0;
+
+	// Allocate match finder's hash array.
+	alloc_count = mf->hash_size_sum + mf->sons_count;
+
+#if UINT32_MAX >= SIZE_MAX / 4
+	// Check for integer overflow. (Huge dictionaries are not
+	// possible on 32-bit CPU.)
+	if (alloc_count > SIZE_MAX / sizeof(uint32_t))
+		return true;
+#endif
+
+	if (mf->hash == NULL) {
+		mf->hash = lzma_alloc(alloc_count * sizeof(uint32_t),
+				allocator);
+		if (mf->hash == NULL)
+			return true;
+	}
+
+	mf->son = mf->hash + mf->hash_size_sum;
+	mf->cyclic_pos = 0;
+
+	// Initialize the hash table. Since EMPTY_HASH_VALUE is zero, we
+	// can use memset().
+/*
+	for (uint32_t i = 0; i < hash_size_sum; ++i)
+		mf->hash[i] = EMPTY_HASH_VALUE;
+*/
+	memzero(mf->hash, (size_t)(mf->hash_size_sum) * sizeof(uint32_t));
+
+	// We don't need to initialize mf->son, but not doing that will
+	// make Valgrind complain in normalization (see normalize() in
+	// lz_encoder_mf.c).
+	//
+	// Skipping this initialization is *very* good when big dictionary is
+	// used but only small amount of data gets actually compressed: most
+	// of the mf->hash won't get actually allocated by the kernel, so
+	// we avoid wasting RAM and improve initialization speed a lot.
+	//memzero(mf->son, (size_t)(mf->sons_count) * sizeof(uint32_t));
+
+	// Handle preset dictionary.
+	if (lz_options->preset_dict != NULL
+			&& lz_options->preset_dict_size > 0) {
+		// If the preset dictionary is bigger than the actual
+		// dictionary, use only the tail.
+		mf->write_pos = my_min(lz_options->preset_dict_size, mf->size);
+		memcpy(mf->buffer, lz_options->preset_dict
+				+ lz_options->preset_dict_size - mf->write_pos,
+				mf->write_pos);
+		mf->action = LZMA_SYNC_FLUSH;
+		mf->skip(mf, mf->write_pos);
+	}
+
+	mf->action = LZMA_RUN;
+
+	return false;
+}
+
+
+extern uint64_t
+lzma_lz_encoder_memusage(const lzma_lz_options *lz_options)
+{
+	// Old buffers must not exist when calling lz_encoder_prepare().
+	lzma_mf mf = { NULL };
+
+	// Setup the size information into mf.
+	if (lz_encoder_prepare(&mf, NULL, lz_options))
+		return UINT64_MAX;
+
+	// Calculate the memory usage.
+	return (uint64_t)(mf.hash_size_sum + mf.sons_count)
+				* sizeof(uint32_t)
+			+ (uint64_t)(mf.size) + sizeof(lzma_coder);
+}
+
+
+static void
+lz_encoder_end(lzma_coder *coder, lzma_allocator *allocator)
+{
+	lzma_next_end(&coder->next, allocator);
+
+	lzma_free(coder->mf.hash, allocator);
+	lzma_free(coder->mf.buffer, allocator);
+
+	if (coder->lz.end != NULL)
+		coder->lz.end(coder->lz.coder, allocator);
+	else
+		lzma_free(coder->lz.coder, allocator);
+
+	lzma_free(coder, allocator);
+	return;
+}
+
+
+static lzma_ret
+lz_encoder_update(lzma_coder *coder, lzma_allocator *allocator,
+		const lzma_filter *filters_null lzma_attribute((__unused__)),
+		const lzma_filter *reversed_filters)
+{
+	if (coder->lz.options_update == NULL)
+		return LZMA_PROG_ERROR;
+
+	return_if_error(coder->lz.options_update(
+			coder->lz.coder, reversed_filters));
+
+	return lzma_next_filter_update(
+			&coder->next, allocator, reversed_filters + 1);
+}
+
+
+extern lzma_ret
+lzma_lz_encoder_init(lzma_next_coder *next, lzma_allocator *allocator,
+		const lzma_filter_info *filters,
+		lzma_ret (*lz_init)(lzma_lz_encoder *lz,
+			lzma_allocator *allocator, const void *options,
+			lzma_lz_options *lz_options))
+{
+	lzma_lz_options lz_options;
+
+#ifdef HAVE_SMALL
+	// We need that the CRC32 table has been initialized.
+	lzma_crc32_init();
+#endif
+
+	// Allocate and initialize the base data structure.
+	if (next->coder == NULL) {
+		next->coder = lzma_alloc(sizeof(lzma_coder), allocator);
+		if (next->coder == NULL)
+			return LZMA_MEM_ERROR;
+
+		next->code = &lz_encode;
+		next->end = &lz_encoder_end;
+		next->update = &lz_encoder_update;
+
+		next->coder->lz.coder = NULL;
+		next->coder->lz.code = NULL;
+		next->coder->lz.end = NULL;
+
+		next->coder->mf.buffer = NULL;
+		next->coder->mf.hash = NULL;
+		next->coder->mf.hash_size_sum = 0;
+		next->coder->mf.sons_count = 0;
+
+		next->coder->next = LZMA_NEXT_CODER_INIT;
+	}
+
+	// Initialize the LZ-based encoder.
+	return_if_error(lz_init(&next->coder->lz, allocator,
+			filters[0].options, &lz_options));
+
+	// Setup the size information into next->coder->mf and deallocate
+	// old buffers if they have wrong size.
+	if (lz_encoder_prepare(&next->coder->mf, allocator, &lz_options))
+		return LZMA_OPTIONS_ERROR;
+
+	// Allocate new buffers if needed, and do the rest of
+	// the initialization.
+	if (lz_encoder_init(&next->coder->mf, allocator, &lz_options))
+		return LZMA_MEM_ERROR;
+
+	// Initialize the next filter in the chain, if any.
+	return lzma_next_filter_init(&next->coder->next, allocator,
+			filters + 1);
+}
+
+
+extern LZMA_API(lzma_bool)
+lzma_mf_is_supported(lzma_match_finder mf)
+{
+	bool ret = false;
+
+#ifdef HAVE_MF_HC3
+	if (mf == LZMA_MF_HC3)
+		ret = true;
+#endif
+
+#ifdef HAVE_MF_HC4
+	if (mf == LZMA_MF_HC4)
+		ret = true;
+#endif
+
+#ifdef HAVE_MF_BT2
+	if (mf == LZMA_MF_BT2)
+		ret = true;
+#endif
+
+#ifdef HAVE_MF_BT3
+	if (mf == LZMA_MF_BT3)
+		ret = true;
+#endif
+
+#ifdef HAVE_MF_BT4
+	if (mf == LZMA_MF_BT4)
+		ret = true;
+#endif
+
+	return ret;
+}
diff --git a/Utilities/cmliblzma/liblzma/lz/lz_encoder.h b/Utilities/cmliblzma/liblzma/lz/lz_encoder.h
new file mode 100644
index 0000000..dcb4b2c
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/lz/lz_encoder.h
@@ -0,0 +1,328 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       lz_encoder.h
+/// \brief      LZ in window and match finder API
+///
+//  Authors:    Igor Pavlov
+//              Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#ifndef LZMA_LZ_ENCODER_H
+#define LZMA_LZ_ENCODER_H
+
+#include "common.h"
+
+
+/// A table of these is used by the LZ-based encoder to hold
+/// the length-distance pairs found by the match finder.
+typedef struct {
+	uint32_t len;
+	uint32_t dist;
+} lzma_match;
+
+
+typedef struct lzma_mf_s lzma_mf;
+struct lzma_mf_s {
+	///////////////
+	// In Window //
+	///////////////
+
+	/// Pointer to buffer with data to be compressed
+	uint8_t *buffer;
+
+	/// Total size of the allocated buffer (that is, including all
+	/// the extra space)
+	uint32_t size;
+
+	/// Number of bytes that must be kept available in our input history.
+	/// That is, once keep_size_before bytes have been processed,
+	/// buffer[read_pos - keep_size_before] is the oldest byte that
+	/// must be available for reading.
+	uint32_t keep_size_before;
+
+	/// Number of bytes that must be kept in buffer after read_pos.
+	/// That is, read_pos <= write_pos - keep_size_after as long as
+	/// action is LZMA_RUN; when action != LZMA_RUN, read_pos is allowed
+	/// to reach write_pos so that the last bytes get encoded too.
+	uint32_t keep_size_after;
+
+	/// Match finders store locations of matches using 32-bit integers.
+	/// To avoid adjusting several megabytes of integers every time the
+	/// input window is moved with move_window, we only adjust the
+	/// offset of the buffer. Thus, buffer[value_in_hash_table - offset]
+	/// is the byte pointed by value_in_hash_table.
+	uint32_t offset;
+
+	/// buffer[read_pos] is the next byte to run through the match
+	/// finder. This is incremented in the match finder once the byte
+	/// has been processed.
+	uint32_t read_pos;
+
+	/// Number of bytes that have been ran through the match finder, but
+	/// which haven't been encoded by the LZ-based encoder yet.
+	uint32_t read_ahead;
+
+	/// As long as read_pos is less than read_limit, there is enough
+	/// input available in buffer for at least one encoding loop.
+	///
+	/// Because of the stateful API, read_limit may and will get greater
+	/// than read_pos quite often. This is taken into account when
+	/// calculating the value for keep_size_after.
+	uint32_t read_limit;
+
+	/// buffer[write_pos] is the first byte that doesn't contain valid
+	/// uncompressed data; that is, the next input byte will be copied
+	/// to buffer[write_pos].
+	uint32_t write_pos;
+
+	/// Number of bytes not hashed before read_pos. This is needed to
+	/// restart the match finder after LZMA_SYNC_FLUSH.
+	uint32_t pending;
+
+	//////////////////
+	// Match Finder //
+	//////////////////
+
+	/// Find matches. Returns the number of distance-length pairs written
+	/// to the matches array. This is called only via lzma_mf_find().
+	uint32_t (*find)(lzma_mf *mf, lzma_match *matches);
+
+	/// Skips num bytes. This is like find() but doesn't make the
+	/// distance-length pairs available, thus being a little faster.
+	/// This is called only via mf_skip().
+	void (*skip)(lzma_mf *mf, uint32_t num);
+
+	uint32_t *hash;
+	uint32_t *son;
+	uint32_t cyclic_pos;
+	uint32_t cyclic_size; // Must be dictionary size + 1.
+	uint32_t hash_mask;
+
+	/// Maximum number of loops in the match finder
+	uint32_t depth;
+
+	/// Maximum length of a match that the match finder will try to find.
+	uint32_t nice_len;
+
+	/// Maximum length of a match supported by the LZ-based encoder.
+	/// If the longest match found by the match finder is nice_len,
+	/// mf_find() tries to expand it up to match_len_max bytes.
+	uint32_t match_len_max;
+
+	/// When running out of input, binary tree match finders need to know
+	/// if it is due to flushing or finishing. The action is used also
+	/// by the LZ-based encoders themselves.
+	lzma_action action;
+
+	/// Number of elements in hash[]
+	uint32_t hash_size_sum;
+
+	/// Number of elements in son[]
+	uint32_t sons_count;
+};
+
+
+typedef struct {
+	/// Extra amount of data to keep available before the "actual"
+	/// dictionary.
+	size_t before_size;
+
+	/// Size of the history buffer
+	size_t dict_size;
+
+	/// Extra amount of data to keep available after the "actual"
+	/// dictionary.
+	size_t after_size;
+
+	/// Maximum length of a match that the LZ-based encoder can accept.
+	/// This is used to extend matches of length nice_len to the
+	/// maximum possible length.
+	size_t match_len_max;
+
+	/// Match finder will search matches up to this length.
+	/// This must be less than or equal to match_len_max.
+	size_t nice_len;
+
+	/// Type of the match finder to use
+	lzma_match_finder match_finder;
+
+	/// Maximum search depth
+	uint32_t depth;
+
+	/// TODO: Comment
+	const uint8_t *preset_dict;
+
+	uint32_t preset_dict_size;
+
+} lzma_lz_options;
+
+
+// The total usable buffer space at any moment outside the match finder:
+// before_size + dict_size + after_size + match_len_max
+//
+// In reality, there's some extra space allocated to prevent the number of
+// memmove() calls reasonable. The bigger the dict_size is, the bigger
+// this extra buffer will be since with bigger dictionaries memmove() would
+// also take longer.
+//
+// A single encoder loop in the LZ-based encoder may call the match finder
+// (mf_find() or mf_skip()) at most after_size times. In other words,
+// a single encoder loop may increment lzma_mf.read_pos at most after_size
+// times. Since matches are looked up to
+// lzma_mf.buffer[lzma_mf.read_pos + match_len_max - 1], the total
+// amount of extra buffer needed after dict_size becomes
+// after_size + match_len_max.
+//
+// before_size has two uses. The first one is to keep literals available
+// in cases when the LZ-based encoder has made some read ahead.
+// TODO: Maybe this could be changed by making the LZ-based encoders to
+// store the actual literals as they do with length-distance pairs.
+//
+// Algorithms such as LZMA2 first try to compress a chunk, and then check
+// if the encoded result is smaller than the uncompressed one. If the chunk
+// was uncompressible, it is better to store it in uncompressed form in
+// the output stream. To do this, the whole uncompressed chunk has to be
+// still available in the history buffer. before_size achieves that.
+
+
+typedef struct {
+	/// Data specific to the LZ-based encoder
+	lzma_coder *coder;
+
+	/// Function to encode from *dict to out[]
+	lzma_ret (*code)(lzma_coder *LZMA_RESTRICT coder,
+			lzma_mf *LZMA_RESTRICT mf, uint8_t *LZMA_RESTRICT out,
+			size_t *LZMA_RESTRICT out_pos, size_t out_size);
+
+	/// Free allocated resources
+	void (*end)(lzma_coder *coder, lzma_allocator *allocator);
+
+	/// Update the options in the middle of the encoding.
+	lzma_ret (*options_update)(lzma_coder *coder,
+			const lzma_filter *filter);
+
+} lzma_lz_encoder;
+
+
+// Basic steps:
+//  1. Input gets copied into the dictionary.
+//  2. Data in dictionary gets run through the match finder byte by byte.
+//  3. The literals and matches are encoded using e.g. LZMA.
+//
+// The bytes that have been ran through the match finder, but not encoded yet,
+// are called `read ahead'.
+
+
+/// Get pointer to the first byte not ran through the match finder
+static inline uint8_t *
+mf_ptr(const lzma_mf *mf)
+{
+	return mf->buffer + mf->read_pos;
+}
+
+
+/// Get the number of bytes that haven't been ran through the match finder yet.
+static inline uint32_t
+mf_avail(const lzma_mf *mf)
+{
+	return mf->write_pos - mf->read_pos;
+}
+
+
+/// Get the number of bytes that haven't been encoded yet (some of these
+/// bytes may have been ran through the match finder though).
+static inline uint32_t
+mf_unencoded(const lzma_mf *mf)
+{
+	return mf->write_pos - mf->read_pos + mf->read_ahead;
+}
+
+
+/// Calculate the absolute offset from the beginning of the most recent
+/// dictionary reset. Only the lowest four bits are important, so there's no
+/// problem that we don't know the 64-bit size of the data encoded so far.
+///
+/// NOTE: When moving the input window, we need to do it so that the lowest
+/// bits of dict->read_pos are not modified to keep this macro working
+/// as intended.
+static inline uint32_t
+mf_position(const lzma_mf *mf)
+{
+	return mf->read_pos - mf->read_ahead;
+}
+
+
+/// Since everything else begins with mf_, use it also for lzma_mf_find().
+#define mf_find lzma_mf_find
+
+
+/// Skip the given number of bytes. This is used when a good match was found.
+/// For example, if mf_find() finds a match of 200 bytes long, the first byte
+/// of that match was already consumed by mf_find(), and the rest 199 bytes
+/// have to be skipped with mf_skip(mf, 199).
+static inline void
+mf_skip(lzma_mf *mf, uint32_t amount)
+{
+	if (amount != 0) {
+		mf->skip(mf, amount);
+		mf->read_ahead += amount;
+	}
+}
+
+
+/// Copies at most *left number of bytes from the history buffer
+/// to out[]. This is needed by LZMA2 to encode uncompressed chunks.
+static inline void
+mf_read(lzma_mf *mf, uint8_t *out, size_t *out_pos, size_t out_size,
+		size_t *left)
+{
+	const size_t out_avail = out_size - *out_pos;
+	const size_t copy_size = my_min(out_avail, *left);
+
+	assert(mf->read_ahead == 0);
+	assert(mf->read_pos >= *left);
+
+	memcpy(out + *out_pos, mf->buffer + mf->read_pos - *left,
+			copy_size);
+
+	*out_pos += copy_size;
+	*left -= copy_size;
+	return;
+}
+
+
+extern lzma_ret lzma_lz_encoder_init(
+		lzma_next_coder *next, lzma_allocator *allocator,
+		const lzma_filter_info *filters,
+		lzma_ret (*lz_init)(lzma_lz_encoder *lz,
+			lzma_allocator *allocator, const void *options,
+			lzma_lz_options *lz_options));
+
+
+extern uint64_t lzma_lz_encoder_memusage(const lzma_lz_options *lz_options);
+
+
+// These are only for LZ encoder's internal use.
+extern uint32_t lzma_mf_find(
+		lzma_mf *mf, uint32_t *count, lzma_match *matches);
+
+extern uint32_t lzma_mf_hc3_find(lzma_mf *dict, lzma_match *matches);
+extern void lzma_mf_hc3_skip(lzma_mf *dict, uint32_t amount);
+
+extern uint32_t lzma_mf_hc4_find(lzma_mf *dict, lzma_match *matches);
+extern void lzma_mf_hc4_skip(lzma_mf *dict, uint32_t amount);
+
+extern uint32_t lzma_mf_bt2_find(lzma_mf *dict, lzma_match *matches);
+extern void lzma_mf_bt2_skip(lzma_mf *dict, uint32_t amount);
+
+extern uint32_t lzma_mf_bt3_find(lzma_mf *dict, lzma_match *matches);
+extern void lzma_mf_bt3_skip(lzma_mf *dict, uint32_t amount);
+
+extern uint32_t lzma_mf_bt4_find(lzma_mf *dict, lzma_match *matches);
+extern void lzma_mf_bt4_skip(lzma_mf *dict, uint32_t amount);
+
+#endif
diff --git a/Utilities/cmliblzma/liblzma/lz/lz_encoder_hash.h b/Utilities/cmliblzma/liblzma/lz/lz_encoder_hash.h
new file mode 100644
index 0000000..de17c54
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/lz/lz_encoder_hash.h
@@ -0,0 +1,105 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       lz_encoder_hash.h
+/// \brief      Hash macros for match finders
+//
+//  Author:     Igor Pavlov
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#ifndef LZMA_LZ_ENCODER_HASH_H
+#define LZMA_LZ_ENCODER_HASH_H
+
+#if defined(WORDS_BIGENDIAN) && !defined(HAVE_SMALL)
+	// This is to make liblzma produce the same output on big endian
+	// systems that it does on little endian systems. lz_encoder.c
+	// takes care of including the actual table.
+	extern const uint32_t lzma_lz_hash_table[256];
+#	define hash_table lzma_lz_hash_table
+#else
+#	include "check.h"
+#	define hash_table lzma_crc32_table[0]
+#endif
+
+#define HASH_2_SIZE (UINT32_C(1) << 10)
+#define HASH_3_SIZE (UINT32_C(1) << 16)
+#define HASH_4_SIZE (UINT32_C(1) << 20)
+
+#define HASH_2_MASK (HASH_2_SIZE - 1)
+#define HASH_3_MASK (HASH_3_SIZE - 1)
+#define HASH_4_MASK (HASH_4_SIZE - 1)
+
+#define FIX_3_HASH_SIZE (HASH_2_SIZE)
+#define FIX_4_HASH_SIZE (HASH_2_SIZE + HASH_3_SIZE)
+#define FIX_5_HASH_SIZE (HASH_2_SIZE + HASH_3_SIZE + HASH_4_SIZE)
+
+// Endianness doesn't matter in hash_2_calc() (no effect on the output).
+#ifdef TUKLIB_FAST_UNALIGNED_ACCESS
+#	define hash_2_calc() \
+		hash_value = *(const uint16_t *)(cur)
+#else
+#	define hash_2_calc() \
+		hash_value = (uint32_t)(cur[0]) | ((uint32_t)(cur[1]) << 8)
+#endif
+
+#define hash_3_calc() \
+	temp = hash_table[cur[0]] ^ cur[1]; \
+	hash_2_value = temp & HASH_2_MASK; \
+	hash_value = (temp ^ ((uint32_t)(cur[2]) << 8)) & mf->hash_mask
+
+#define hash_4_calc() \
+	temp = hash_table[cur[0]] ^ cur[1]; \
+	hash_2_value = temp & HASH_2_MASK; \
+	hash_3_value = (temp ^ ((uint32_t)(cur[2]) << 8)) & HASH_3_MASK; \
+	hash_value = (temp ^ ((uint32_t)(cur[2]) << 8) \
+			^ (hash_table[cur[3]] << 5)) & mf->hash_mask
+
+
+// The following are not currently used.
+
+#define hash_5_calc() \
+	const uint32_t temp = hash_table[cur[0]] ^ cur[1]; \
+	const uint32_t hash_2_value = temp & HASH_2_MASK; \
+	const uint32_t hash_3_value \
+			= (temp ^ ((uint32_t)(cur[2]) << 8)) & HASH_3_MASK; \
+	uint32_t hash_4_value = (temp ^ ((uint32_t)(cur[2]) << 8) ^ \
+			^ hash_table[cur[3]] << 5); \
+	const uint32_t hash_value \
+			= (hash_4_value ^ (hash_table[cur[4]] << 3)) \
+				& mf->hash_mask; \
+	hash_4_value &= HASH_4_MASK
+
+/*
+#define hash_zip_calc() \
+	const uint32_t hash_value \
+			= (((uint32_t)(cur[0]) | ((uint32_t)(cur[1]) << 8)) \
+				^ hash_table[cur[2]]) & 0xFFFF
+*/
+
+#define hash_zip_calc() \
+	const uint32_t hash_value \
+			= (((uint32_t)(cur[2]) | ((uint32_t)(cur[0]) << 8)) \
+				^ hash_table[cur[1]]) & 0xFFFF
+
+#define mt_hash_2_calc() \
+	const uint32_t hash_2_value \
+			= (hash_table[cur[0]] ^ cur[1]) & HASH_2_MASK
+
+#define mt_hash_3_calc() \
+	const uint32_t temp = hash_table[cur[0]] ^ cur[1]; \
+	const uint32_t hash_2_value = temp & HASH_2_MASK; \
+	const uint32_t hash_3_value \
+			= (temp ^ ((uint32_t)(cur[2]) << 8)) & HASH_3_MASK
+
+#define mt_hash_4_calc() \
+	const uint32_t temp = hash_table[cur[0]] ^ cur[1]; \
+	const uint32_t hash_2_value = temp & HASH_2_MASK; \
+	const uint32_t hash_3_value \
+			= (temp ^ ((uint32_t)(cur[2]) << 8)) & HASH_3_MASK; \
+	const uint32_t hash_4_value = (temp ^ ((uint32_t)(cur[2]) << 8) ^ \
+			(hash_table[cur[3]] << 5)) & HASH_4_MASK
+
+#endif
diff --git a/Utilities/cmliblzma/liblzma/lz/lz_encoder_hash_table.h b/Utilities/cmliblzma/liblzma/lz/lz_encoder_hash_table.h
new file mode 100644
index 0000000..8c51717
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/lz/lz_encoder_hash_table.h
@@ -0,0 +1,68 @@
+/* This file has been automatically generated by crc32_tablegen.c. */
+
+const uint32_t lzma_lz_hash_table[256] = {
+	0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA,
+	0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3,
+	0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988,
+	0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91,
+	0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE,
+	0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7,
+	0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC,
+	0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5,
+	0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172,
+	0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
+	0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940,
+	0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,
+	0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116,
+	0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F,
+	0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,
+	0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D,
+	0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A,
+	0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433,
+	0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818,
+	0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
+	0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E,
+	0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457,
+	0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C,
+	0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65,
+	0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2,
+	0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB,
+	0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0,
+	0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9,
+	0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086,
+	0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
+	0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4,
+	0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD,
+	0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A,
+	0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683,
+	0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8,
+	0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,
+	0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE,
+	0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7,
+	0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC,
+	0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,
+	0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252,
+	0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,
+	0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60,
+	0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79,
+	0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,
+	0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F,
+	0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04,
+	0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D,
+	0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A,
+	0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,
+	0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38,
+	0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21,
+	0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E,
+	0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777,
+	0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C,
+	0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45,
+	0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2,
+	0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB,
+	0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0,
+	0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
+	0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6,
+	0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF,
+	0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94,
+	0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D
+};
diff --git a/Utilities/cmliblzma/liblzma/lz/lz_encoder_mf.c b/Utilities/cmliblzma/liblzma/lz/lz_encoder_mf.c
new file mode 100644
index 0000000..50c3459
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/lz/lz_encoder_mf.c
@@ -0,0 +1,814 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       lz_encoder_mf.c
+/// \brief      Match finders
+///
+//  Authors:    Igor Pavlov
+//              Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "lz_encoder.h"
+#include "lz_encoder_hash.h"
+
+
+/// \brief      Find matches starting from the current byte
+///
+/// \return     The length of the longest match found
+extern uint32_t
+lzma_mf_find(lzma_mf *mf, uint32_t *count_ptr, lzma_match *matches)
+{
+	// Call the match finder. It returns the number of length-distance
+	// pairs found.
+	// FIXME: Minimum count is zero, what _exactly_ is the maximum?
+	const uint32_t count = mf->find(mf, matches);
+
+	// Length of the longest match; assume that no matches were found
+	// and thus the maximum length is zero.
+	uint32_t len_best = 0;
+
+	if (count > 0) {
+#ifndef NDEBUG
+		uint32_t i;
+		// Validate the matches.
+		for (i = 0; i < count; ++i) {
+			assert(matches[i].len <= mf->nice_len);
+			assert(matches[i].dist < mf->read_pos);
+			assert(memcmp(mf_ptr(mf) - 1,
+				mf_ptr(mf) - matches[i].dist - 2,
+				matches[i].len) == 0);
+		}
+#endif
+
+		// The last used element in the array contains
+		// the longest match.
+		len_best = matches[count - 1].len;
+
+		// If a match of maximum search length was found, try to
+		// extend the match to maximum possible length.
+		if (len_best == mf->nice_len) {
+			uint8_t *p1;
+			uint8_t *p2;
+
+			// The limit for the match length is either the
+			// maximum match length supported by the LZ-based
+			// encoder or the number of bytes left in the
+			// dictionary, whichever is smaller.
+			uint32_t limit = mf_avail(mf) + 1;
+			if (limit > mf->match_len_max)
+				limit = mf->match_len_max;
+
+			// Pointer to the byte we just ran through
+			// the match finder.
+			p1 = mf_ptr(mf) - 1;
+
+			// Pointer to the beginning of the match. We need -1
+			// here because the match distances are zero based.
+			p2 = p1 - matches[count - 1].dist - 1;
+
+			while (len_best < limit
+					&& p1[len_best] == p2[len_best])
+				++len_best;
+		}
+	}
+
+	*count_ptr = count;
+
+	// Finally update the read position to indicate that match finder was
+	// run for this dictionary offset.
+	++mf->read_ahead;
+
+	return len_best;
+}
+
+
+/// Hash value to indicate unused element in the hash. Since we start the
+/// positions from dict_size + 1, zero is always too far to qualify
+/// as usable match position.
+#define EMPTY_HASH_VALUE 0
+
+
+/// Normalization must be done when lzma_mf.offset + lzma_mf.read_pos
+/// reaches MUST_NORMALIZE_POS.
+#define MUST_NORMALIZE_POS UINT32_MAX
+
+
+/// \brief      Normalizes hash values
+///
+/// The hash arrays store positions of match candidates. The positions are
+/// relative to an arbitrary offset that is not the same as the absolute
+/// offset in the input stream. The relative position of the current byte
+/// is lzma_mf.offset + lzma_mf.read_pos. The distances of the matches are
+/// the differences of the current read position and the position found from
+/// the hash.
+///
+/// To prevent integer overflows of the offsets stored in the hash arrays,
+/// we need to "normalize" the stored values now and then. During the
+/// normalization, we drop values that indicate distance greater than the
+/// dictionary size, thus making space for new values.
+static void
+normalize(lzma_mf *mf)
+{
+	uint32_t i;
+	uint32_t subvalue;
+	uint32_t count;
+	uint32_t *hash;
+
+	assert(mf->read_pos + mf->offset == MUST_NORMALIZE_POS);
+
+	// In future we may not want to touch the lowest bits, because there
+	// may be match finders that use larger resolution than one byte.
+	subvalue = (MUST_NORMALIZE_POS - mf->cyclic_size);
+				// & (~(UINT32_C(1) << 10) - 1);
+
+	count = mf->hash_size_sum + mf->sons_count;
+	hash = mf->hash;
+
+	for (i = 0; i < count; ++i) {
+		// If the distance is greater than the dictionary size,
+		// we can simply mark the hash element as empty.
+		//
+		// NOTE: Only the first mf->hash_size_sum elements are
+		// initialized for sure. There may be uninitialized elements
+		// in mf->son. Since we go through both mf->hash and
+		// mf->son here in normalization, Valgrind may complain
+		// that the "if" below depends on uninitialized value. In
+		// this case it is safe to ignore the warning. See also the
+		// comments in lz_encoder_init() in lz_encoder.c.
+		if (hash[i] <= subvalue)
+			hash[i] = EMPTY_HASH_VALUE;
+		else
+			hash[i] -= subvalue;
+	}
+
+	// Update offset to match the new locations.
+	mf->offset -= subvalue;
+
+	return;
+}
+
+
+/// Mark the current byte as processed from point of view of the match finder.
+static void
+move_pos(lzma_mf *mf)
+{
+	if (++mf->cyclic_pos == mf->cyclic_size)
+		mf->cyclic_pos = 0;
+
+	++mf->read_pos;
+	assert(mf->read_pos <= mf->write_pos);
+
+	if (unlikely(mf->read_pos + mf->offset == UINT32_MAX))
+		normalize(mf);
+}
+
+
+/// When flushing, we cannot run the match finder unless there is nice_len
+/// bytes available in the dictionary. Instead, we skip running the match
+/// finder (indicating that no match was found), and count how many bytes we
+/// have ignored this way.
+///
+/// When new data is given after the flushing was completed, the match finder
+/// is restarted by rewinding mf->read_pos backwards by mf->pending. Then
+/// the missed bytes are added to the hash using the match finder's skip
+/// function (with small amount of input, it may start using mf->pending
+/// again if flushing).
+///
+/// Due to this rewinding, we don't touch cyclic_pos or test for
+/// normalization. It will be done when the match finder's skip function
+/// catches up after a flush.
+static void
+move_pending(lzma_mf *mf)
+{
+	++mf->read_pos;
+	assert(mf->read_pos <= mf->write_pos);
+	++mf->pending;
+}
+
+
+/// Calculate len_limit and determine if there is enough input to run
+/// the actual match finder code. Sets up "cur" and "pos". This macro
+/// is used by all find functions and binary tree skip functions. Hash
+/// chain skip function doesn't need len_limit so a simpler code is used
+/// in them.
+#define header(is_bt, len_min, ret_op) \
+	uint32_t len_limit = mf_avail(mf); \
+	if (mf->nice_len <= len_limit) { \
+		len_limit = mf->nice_len; \
+	} else if (len_limit < (len_min) \
+			|| (is_bt && mf->action == LZMA_SYNC_FLUSH)) { \
+		assert(mf->action != LZMA_RUN); \
+		move_pending(mf); \
+		ret_op; \
+	} \
+	cur = mf_ptr(mf); \
+	pos = mf->read_pos + mf->offset
+
+
+/// Header for find functions. "return 0" indicates that zero matches
+/// were found.
+#define header_find(is_bt, len_min) \
+	header(is_bt, len_min, return 0)
+
+
+/// Header for a loop in a skip function. "continue" tells to skip the rest
+/// of the code in the loop.
+#define header_skip(is_bt, len_min) \
+	header(is_bt, len_min, continue)
+
+
+/// Calls hc_find_func() or bt_find_func() and calculates the total number
+/// of matches found. Updates the dictionary position and returns the number
+/// of matches found.
+#define call_find(func, len_best) \
+do { \
+	matches_count = func(len_limit, pos, cur, cur_match, mf->depth, \
+				mf->son, mf->cyclic_pos, mf->cyclic_size, \
+				matches + matches_count, len_best) \
+			- matches; \
+	move_pos(mf); \
+	return matches_count; \
+} while (0)
+
+
+////////////////
+// Hash Chain //
+////////////////
+
+#if defined(HAVE_MF_HC3) || defined(HAVE_MF_HC4)
+///
+///
+/// \param      len_limit       Don't look for matches longer than len_limit.
+/// \param      pos             lzma_mf.read_pos + lzma_mf.offset
+/// \param      cur             Pointer to current byte (mf_ptr(mf))
+/// \param      cur_match       Start position of the current match candidate
+/// \param      depth           Maximum length of the hash chain
+/// \param      son             lzma_mf.son (contains the hash chain)
+/// \param      cyclic_pos
+/// \param      cyclic_size
+/// \param      matches         Array to hold the matches.
+/// \param      len_best        The length of the longest match found so far.
+static lzma_match *
+hc_find_func(
+		const uint32_t len_limit,
+		const uint32_t pos,
+		const uint8_t *const cur,
+		uint32_t cur_match,
+		uint32_t depth,
+		uint32_t *const son,
+		const uint32_t cyclic_pos,
+		const uint32_t cyclic_size,
+		lzma_match *matches,
+		uint32_t len_best)
+{
+	son[cyclic_pos] = cur_match;
+
+	while (true) {
+		const uint32_t delta = pos - cur_match;
+		const uint8_t *pb;
+		if (depth-- == 0 || delta >= cyclic_size)
+			return matches;
+
+		pb = cur - delta;
+		cur_match = son[cyclic_pos - delta
+				+ (delta > cyclic_pos ? cyclic_size : 0)];
+
+		if (pb[len_best] == cur[len_best] && pb[0] == cur[0]) {
+			uint32_t len = 0;
+			while (++len != len_limit)
+				if (pb[len] != cur[len])
+					break;
+
+			if (len_best < len) {
+				len_best = len;
+				matches->len = len;
+				matches->dist = delta - 1;
+				++matches;
+
+				if (len == len_limit)
+					return matches;
+			}
+		}
+	}
+}
+
+
+#define hc_find(len_best) \
+	call_find(hc_find_func, len_best)
+
+
+#define hc_skip() \
+do { \
+	mf->son[mf->cyclic_pos] = cur_match; \
+	move_pos(mf); \
+} while (0)
+
+#endif
+
+
+#ifdef HAVE_MF_HC3
+extern uint32_t
+lzma_mf_hc3_find(lzma_mf *mf, lzma_match *matches)
+{
+	const uint8_t *cur;
+	uint32_t pos;
+	uint32_t temp, hash_value, hash_2_value; /* hash_3_calc */
+	uint32_t delta2, cur_match;
+	uint32_t len_best = 2;
+	uint32_t matches_count = 0;
+
+	header_find(false, 3);
+
+	hash_3_calc();
+
+	delta2 = pos - mf->hash[hash_2_value];
+	cur_match = mf->hash[FIX_3_HASH_SIZE + hash_value];
+
+	mf->hash[hash_2_value] = pos;
+	mf->hash[FIX_3_HASH_SIZE + hash_value] = pos;
+
+	if (delta2 < mf->cyclic_size && *(cur - delta2) == *cur) {
+		for ( ; len_best != len_limit; ++len_best)
+			if (*(cur + len_best - delta2) != cur[len_best])
+				break;
+
+		matches[0].len = len_best;
+		matches[0].dist = delta2 - 1;
+		matches_count = 1;
+
+		if (len_best == len_limit) {
+			hc_skip();
+			return 1; // matches_count
+		}
+	}
+
+	hc_find(len_best);
+}
+
+
+extern void
+lzma_mf_hc3_skip(lzma_mf *mf, uint32_t amount)
+{
+	do {
+		const uint8_t *cur;
+		uint32_t pos;
+		uint32_t temp, hash_value, hash_2_value; /* hash_3_calc */
+		uint32_t cur_match;
+
+		if (mf_avail(mf) < 3) {
+			move_pending(mf);
+			continue;
+		}
+
+		cur = mf_ptr(mf);
+		pos = mf->read_pos + mf->offset;
+
+		hash_3_calc();
+
+		cur_match = mf->hash[FIX_3_HASH_SIZE + hash_value];
+
+		mf->hash[hash_2_value] = pos;
+		mf->hash[FIX_3_HASH_SIZE + hash_value] = pos;
+
+		hc_skip();
+
+	} while (--amount != 0);
+}
+#endif
+
+
+#ifdef HAVE_MF_HC4
+extern uint32_t
+lzma_mf_hc4_find(lzma_mf *mf, lzma_match *matches)
+{
+	const uint8_t *cur;
+	uint32_t pos;
+	uint32_t temp, hash_value, hash_2_value, hash_3_value; /* hash_4_calc */
+	uint32_t delta2, delta3, cur_match;
+	uint32_t len_best = 1;
+	uint32_t matches_count = 0;
+
+	header_find(false, 4);
+
+	hash_4_calc();
+
+	delta2 = pos - mf->hash[hash_2_value];
+	delta3 = pos - mf->hash[FIX_3_HASH_SIZE + hash_3_value];
+	cur_match = mf->hash[FIX_4_HASH_SIZE + hash_value];
+
+	mf->hash[hash_2_value ] = pos;
+	mf->hash[FIX_3_HASH_SIZE + hash_3_value] = pos;
+	mf->hash[FIX_4_HASH_SIZE + hash_value] = pos;
+
+	if (delta2 < mf->cyclic_size && *(cur - delta2) == *cur) {
+		len_best = 2;
+		matches[0].len = 2;
+		matches[0].dist = delta2 - 1;
+		matches_count = 1;
+	}
+
+	if (delta2 != delta3 && delta3 < mf->cyclic_size
+			&& *(cur - delta3) == *cur) {
+		len_best = 3;
+		matches[matches_count++].dist = delta3 - 1;
+		delta2 = delta3;
+	}
+
+	if (matches_count != 0) {
+		for ( ; len_best != len_limit; ++len_best)
+			if (*(cur + len_best - delta2) != cur[len_best])
+				break;
+
+		matches[matches_count - 1].len = len_best;
+
+		if (len_best == len_limit) {
+			hc_skip();
+			return matches_count;
+		}
+	}
+
+	if (len_best < 3)
+		len_best = 3;
+
+	hc_find(len_best);
+}
+
+
+extern void
+lzma_mf_hc4_skip(lzma_mf *mf, uint32_t amount)
+{
+	do {
+		const uint8_t *cur;
+		uint32_t pos;
+		uint32_t temp, hash_value, hash_2_value, hash_3_value; /* hash_4_calc */
+		uint32_t cur_match;
+
+		if (mf_avail(mf) < 4) {
+			move_pending(mf);
+			continue;
+		}
+
+		cur = mf_ptr(mf);
+		pos = mf->read_pos + mf->offset;
+
+		hash_4_calc();
+
+		cur_match = mf->hash[FIX_4_HASH_SIZE + hash_value];
+
+		mf->hash[hash_2_value] = pos;
+		mf->hash[FIX_3_HASH_SIZE + hash_3_value] = pos;
+		mf->hash[FIX_4_HASH_SIZE + hash_value] = pos;
+
+		hc_skip();
+
+	} while (--amount != 0);
+}
+#endif
+
+
+/////////////////
+// Binary Tree //
+/////////////////
+
+#if defined(HAVE_MF_BT2) || defined(HAVE_MF_BT3) || defined(HAVE_MF_BT4)
+static lzma_match *
+bt_find_func(
+		const uint32_t len_limit,
+		const uint32_t pos,
+		const uint8_t *const cur,
+		uint32_t cur_match,
+		uint32_t depth,
+		uint32_t *const son,
+		const uint32_t cyclic_pos,
+		const uint32_t cyclic_size,
+		lzma_match *matches,
+		uint32_t len_best)
+{
+	uint32_t *ptr0 = son + (cyclic_pos << 1) + 1;
+	uint32_t *ptr1 = son + (cyclic_pos << 1);
+
+	uint32_t len0 = 0;
+	uint32_t len1 = 0;
+
+	while (true) {
+		uint32_t *pair;
+		const uint8_t *pb;
+		uint32_t len;
+
+		const uint32_t delta = pos - cur_match;
+		if (depth-- == 0 || delta >= cyclic_size) {
+			*ptr0 = EMPTY_HASH_VALUE;
+			*ptr1 = EMPTY_HASH_VALUE;
+			return matches;
+		}
+
+		pair = son + ((cyclic_pos - delta
+				+ (delta > cyclic_pos ? cyclic_size : 0))
+				<< 1);
+
+		pb = cur - delta;
+		len = my_min(len0, len1);
+
+		if (pb[len] == cur[len]) {
+			while (++len != len_limit)
+				if (pb[len] != cur[len])
+					break;
+
+			if (len_best < len) {
+				len_best = len;
+				matches->len = len;
+				matches->dist = delta - 1;
+				++matches;
+
+				if (len == len_limit) {
+					*ptr1 = pair[0];
+					*ptr0 = pair[1];
+					return matches;
+				}
+			}
+		}
+
+		if (pb[len] < cur[len]) {
+			*ptr1 = cur_match;
+			ptr1 = pair + 1;
+			cur_match = *ptr1;
+			len1 = len;
+		} else {
+			*ptr0 = cur_match;
+			ptr0 = pair;
+			cur_match = *ptr0;
+			len0 = len;
+		}
+	}
+}
+
+
+static void
+bt_skip_func(
+		const uint32_t len_limit,
+		const uint32_t pos,
+		const uint8_t *const cur,
+		uint32_t cur_match,
+		uint32_t depth,
+		uint32_t *const son,
+		const uint32_t cyclic_pos,
+		const uint32_t cyclic_size)
+{
+	uint32_t *ptr0 = son + (cyclic_pos << 1) + 1;
+	uint32_t *ptr1 = son + (cyclic_pos << 1);
+
+	uint32_t len0 = 0;
+	uint32_t len1 = 0;
+
+	while (true) {
+		uint32_t *pair;
+		const uint8_t *pb;
+		uint32_t len;
+
+		const uint32_t delta = pos - cur_match;
+		if (depth-- == 0 || delta >= cyclic_size) {
+			*ptr0 = EMPTY_HASH_VALUE;
+			*ptr1 = EMPTY_HASH_VALUE;
+			return;
+		}
+
+		pair = son + ((cyclic_pos - delta
+				+ (delta > cyclic_pos ? cyclic_size : 0))
+				<< 1);
+		pb = cur - delta;
+		len = my_min(len0, len1);
+
+		if (pb[len] == cur[len]) {
+			while (++len != len_limit)
+				if (pb[len] != cur[len])
+					break;
+
+			if (len == len_limit) {
+				*ptr1 = pair[0];
+				*ptr0 = pair[1];
+				return;
+			}
+		}
+
+		if (pb[len] < cur[len]) {
+			*ptr1 = cur_match;
+			ptr1 = pair + 1;
+			cur_match = *ptr1;
+			len1 = len;
+		} else {
+			*ptr0 = cur_match;
+			ptr0 = pair;
+			cur_match = *ptr0;
+			len0 = len;
+		}
+	}
+}
+
+
+#define bt_find(len_best) \
+	call_find(bt_find_func, len_best)
+
+#define bt_skip() \
+do { \
+	bt_skip_func(len_limit, pos, cur, cur_match, mf->depth, \
+			mf->son, mf->cyclic_pos, \
+			mf->cyclic_size); \
+	move_pos(mf); \
+} while (0)
+
+#endif
+
+
+#ifdef HAVE_MF_BT2
+extern uint32_t
+lzma_mf_bt2_find(lzma_mf *mf, lzma_match *matches)
+{
+	const uint8_t *cur;
+	uint32_t pos;
+	uint32_t hash_value; /* hash_2_calc */
+	uint32_t cur_match;
+	uint32_t matches_count = 0;
+
+	header_find(true, 2);
+
+	hash_2_calc();
+
+	cur_match = mf->hash[hash_value];
+	mf->hash[hash_value] = pos;
+
+	bt_find(1);
+}
+
+
+extern void
+lzma_mf_bt2_skip(lzma_mf *mf, uint32_t amount)
+{
+	do {
+		const uint8_t *cur;
+		uint32_t pos;
+		uint32_t hash_value; /* hash_2_calc */
+		uint32_t cur_match;
+
+		header_skip(true, 2);
+
+		hash_2_calc();
+
+		cur_match = mf->hash[hash_value];
+		mf->hash[hash_value] = pos;
+
+		bt_skip();
+
+	} while (--amount != 0);
+}
+#endif
+
+
+#ifdef HAVE_MF_BT3
+extern uint32_t
+lzma_mf_bt3_find(lzma_mf *mf, lzma_match *matches)
+{
+	const uint8_t *cur;
+	uint32_t pos;
+	uint32_t temp, hash_value, hash_2_value; /* hash_3_calc */
+	uint32_t delta2, cur_match;
+	uint32_t len_best = 2;
+	uint32_t matches_count = 0;
+
+	header_find(true, 3);
+
+	hash_3_calc();
+
+	delta2 = pos - mf->hash[hash_2_value];
+	cur_match = mf->hash[FIX_3_HASH_SIZE + hash_value];
+
+	mf->hash[hash_2_value] = pos;
+	mf->hash[FIX_3_HASH_SIZE + hash_value] = pos;
+
+	if (delta2 < mf->cyclic_size && *(cur - delta2) == *cur) {
+		for ( ; len_best != len_limit; ++len_best)
+			if (*(cur + len_best - delta2) != cur[len_best])
+				break;
+
+		matches[0].len = len_best;
+		matches[0].dist = delta2 - 1;
+		matches_count = 1;
+
+		if (len_best == len_limit) {
+			bt_skip();
+			return 1; // matches_count
+		}
+	}
+
+	bt_find(len_best);
+}
+
+
+extern void
+lzma_mf_bt3_skip(lzma_mf *mf, uint32_t amount)
+{
+	do {
+		const uint8_t *cur;
+		uint32_t pos;
+		uint32_t temp, hash_value, hash_2_value; /* hash_3_calc */
+		uint32_t cur_match;
+
+		header_skip(true, 3);
+
+		hash_3_calc();
+
+		cur_match = mf->hash[FIX_3_HASH_SIZE + hash_value];
+
+		mf->hash[hash_2_value] = pos;
+		mf->hash[FIX_3_HASH_SIZE + hash_value] = pos;
+
+		bt_skip();
+
+	} while (--amount != 0);
+}
+#endif
+
+
+#ifdef HAVE_MF_BT4
+extern uint32_t
+lzma_mf_bt4_find(lzma_mf *mf, lzma_match *matches)
+{
+	const uint8_t *cur;
+	uint32_t pos;
+	uint32_t temp, hash_value, hash_2_value, hash_3_value; /* hash_4_calc */
+	uint32_t delta2, delta3, cur_match;
+	uint32_t len_best = 1;
+	uint32_t matches_count = 0;
+
+	header_find(true, 4);
+
+	hash_4_calc();
+
+	delta2 = pos - mf->hash[hash_2_value];
+	delta3 = pos - mf->hash[FIX_3_HASH_SIZE + hash_3_value];
+	cur_match = mf->hash[FIX_4_HASH_SIZE + hash_value];
+
+	mf->hash[hash_2_value] = pos;
+	mf->hash[FIX_3_HASH_SIZE + hash_3_value] = pos;
+	mf->hash[FIX_4_HASH_SIZE + hash_value] = pos;
+
+	if (delta2 < mf->cyclic_size && *(cur - delta2) == *cur) {
+		len_best = 2;
+		matches[0].len = 2;
+		matches[0].dist = delta2 - 1;
+		matches_count = 1;
+	}
+
+	if (delta2 != delta3 && delta3 < mf->cyclic_size
+			&& *(cur - delta3) == *cur) {
+		len_best = 3;
+		matches[matches_count++].dist = delta3 - 1;
+		delta2 = delta3;
+	}
+
+	if (matches_count != 0) {
+		for ( ; len_best != len_limit; ++len_best)
+			if (*(cur + len_best - delta2) != cur[len_best])
+				break;
+
+		matches[matches_count - 1].len = len_best;
+
+		if (len_best == len_limit) {
+			bt_skip();
+			return matches_count;
+		}
+	}
+
+	if (len_best < 3)
+		len_best = 3;
+
+	bt_find(len_best);
+}
+
+
+extern void
+lzma_mf_bt4_skip(lzma_mf *mf, uint32_t amount)
+{
+	do {
+		const uint8_t *cur;
+		uint32_t pos;
+		uint32_t temp, hash_value, hash_2_value, hash_3_value; /* hash_4_calc */
+		uint32_t cur_match;
+
+		header_skip(true, 4);
+
+		hash_4_calc();
+
+		cur_match = mf->hash[FIX_4_HASH_SIZE + hash_value];
+
+		mf->hash[hash_2_value] = pos;
+		mf->hash[FIX_3_HASH_SIZE + hash_3_value] = pos;
+		mf->hash[FIX_4_HASH_SIZE + hash_value] = pos;
+
+		bt_skip();
+
+	} while (--amount != 0);
+}
+#endif
diff --git a/Utilities/cmliblzma/liblzma/lzma/fastpos.h b/Utilities/cmliblzma/liblzma/lzma/fastpos.h
new file mode 100644
index 0000000..5a834d6
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/lzma/fastpos.h
@@ -0,0 +1,142 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       fastpos.h
+/// \brief      Kind of two-bit version of bit scan reverse
+///
+//  Authors:    Igor Pavlov
+//              Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#ifndef LZMA_FASTPOS_H
+#define LZMA_FASTPOS_H
+
+// LZMA encodes match distances (positions) by storing the highest two
+// bits using a six-bit value [0, 63], and then the missing lower bits.
+// Dictionary size is also stored using this encoding in the new .lzma
+// file format header.
+//
+// fastpos.h provides a way to quickly find out the correct six-bit
+// values. The following table gives some examples of this encoding:
+//
+//      pos   return
+//       0       0
+//       1       1
+//       2       2
+//       3       3
+//       4       4
+//       5       4
+//       6       5
+//       7       5
+//       8       6
+//      11       6
+//      12       7
+//     ...      ...
+//      15       7
+//      16       8
+//      17       8
+//     ...      ...
+//      23       8
+//      24       9
+//      25       9
+//     ...      ...
+//
+//
+// Provided functions or macros
+// ----------------------------
+//
+// get_pos_slot(pos) is the basic version. get_pos_slot_2(pos)
+// assumes that pos >= FULL_DISTANCES, thus the result is at least
+// FULL_DISTANCES_BITS * 2. Using get_pos_slot(pos) instead of
+// get_pos_slot_2(pos) would give the same result, but get_pos_slot_2(pos)
+// should be tiny bit faster due to the assumption being made.
+//
+//
+// Size vs. speed
+// --------------
+//
+// With some CPUs that have fast BSR (bit scan reverse) instruction, the
+// size optimized version is slightly faster than the bigger table based
+// approach. Such CPUs include Intel Pentium Pro, Pentium II, Pentium III
+// and Core 2 (possibly others). AMD K7 seems to have slower BSR, but that
+// would still have speed roughly comparable to the table version. Older
+// x86 CPUs like the original Pentium have very slow BSR; on those systems
+// the table version is a lot faster.
+//
+// On some CPUs, the table version is a lot faster when using position
+// dependent code, but with position independent code the size optimized
+// version is slightly faster. This occurs at least on 32-bit SPARC (no
+// ASM optimizations).
+//
+// I'm making the table version the default, because that has good speed
+// on all systems I have tried. The size optimized version is sometimes
+// slightly faster, but sometimes it is a lot slower.
+
+#include "config.h"
+
+#ifdef HAVE_SMALL
+#	define get_pos_slot(pos) ((pos) <= 4 ? (pos) : get_pos_slot_2(pos))
+
+static inline uint32_t
+get_pos_slot_2(uint32_t pos)
+{
+	const uint32_t i = bsr32(pos);
+	return (i + i) + ((pos >> (i - 1)) & 1);
+}
+
+
+#else
+
+#define FASTPOS_BITS 13
+
+extern const uint8_t lzma_fastpos[1 << FASTPOS_BITS];
+
+
+#define fastpos_shift(extra, n) \
+	((extra) + (n) * (FASTPOS_BITS - 1))
+
+#define fastpos_limit(extra, n) \
+	(UINT32_C(1) << (FASTPOS_BITS + fastpos_shift(extra, n)))
+
+#define fastpos_result(pos, extra, n) \
+	lzma_fastpos[(pos) >> fastpos_shift(extra, n)] \
+			+ 2 * fastpos_shift(extra, n)
+
+
+static inline uint32_t
+get_pos_slot(uint32_t pos)
+{
+	// If it is small enough, we can pick the result directly from
+	// the precalculated table.
+	if (pos < fastpos_limit(0, 0))
+		return lzma_fastpos[pos];
+
+	if (pos < fastpos_limit(0, 1))
+		return fastpos_result(pos, 0, 1);
+
+	return fastpos_result(pos, 0, 2);
+}
+
+
+#ifdef FULL_DISTANCES_BITS
+static inline uint32_t
+get_pos_slot_2(uint32_t pos)
+{
+	assert(pos >= FULL_DISTANCES);
+
+	if (pos < fastpos_limit(FULL_DISTANCES_BITS - 1, 0))
+		return fastpos_result(pos, FULL_DISTANCES_BITS - 1, 0);
+
+	if (pos < fastpos_limit(FULL_DISTANCES_BITS - 1, 1))
+		return fastpos_result(pos, FULL_DISTANCES_BITS - 1, 1);
+
+	return fastpos_result(pos, FULL_DISTANCES_BITS - 1, 2);
+}
+#endif
+
+#endif
+
+#endif
diff --git a/Utilities/cmliblzma/liblzma/lzma/fastpos_table.c b/Utilities/cmliblzma/liblzma/lzma/fastpos_table.c
new file mode 100644
index 0000000..6a3ceac
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/lzma/fastpos_table.c
@@ -0,0 +1,519 @@
+/* This file has been automatically generated by fastpos_tablegen.c. */
+
+#include "common.h"
+#include "fastpos.h"
+
+const uint8_t lzma_fastpos[1 << FASTPOS_BITS] = {
+	  0,  1,  2,  3,  4,  4,  5,  5,  6,  6,  6,  6,  7,  7,  7,  7,
+	  8,  8,  8,  8,  8,  8,  8,  8,  9,  9,  9,  9,  9,  9,  9,  9,
+	 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
+	 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
+	 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+	 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+	 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+	 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+	 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+	 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+	 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+	 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+	 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+	 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+	 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+	 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+	 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
+	 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
+	 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
+	 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
+	 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
+	 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
+	 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
+	 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
+	 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
+	 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
+	 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
+	 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
+	 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
+	 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
+	 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
+	 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
+	 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
+	 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
+	 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
+	 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
+	 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
+	 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
+	 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
+	 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
+	 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
+	 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
+	 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
+	 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
+	 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
+	 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
+	 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
+	 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
+	 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+	 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+	 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+	 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+	 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+	 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+	 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+	 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+	 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+	 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+	 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+	 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+	 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+	 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+	 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+	 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+	 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+	 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+	 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+	 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+	 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+	 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+	 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+	 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+	 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+	 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+	 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+	 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+	 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+	 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+	 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+	 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+	 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+	 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+	 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+	 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+	 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+	 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+	 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+	 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+	 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+	 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+	 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+	 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+	 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+	 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+	 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+	 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+	 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
+	 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
+	 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
+	 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
+	 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
+	 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
+	 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
+	 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
+	 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
+	 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
+	 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
+	 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
+	 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
+	 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
+	 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
+	 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
+	 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
+	 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
+	 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
+	 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
+	 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
+	 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
+	 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
+	 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
+	 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
+	 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
+	 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
+	 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
+	 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
+	 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
+	 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
+	 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+	 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25
+};
diff --git a/Utilities/cmliblzma/liblzma/lzma/fastpos_tablegen.c b/Utilities/cmliblzma/liblzma/lzma/fastpos_tablegen.c
new file mode 100644
index 0000000..c97e6f4
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/lzma/fastpos_tablegen.c
@@ -0,0 +1,56 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       fastpos_tablegen.c
+/// \brief      Generates the lzma_fastpos[] lookup table
+///
+//  Authors:    Igor Pavlov
+//              Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include <sys/types.h>
+#include <inttypes.h>
+#include <stdio.h>
+#include "fastpos.h"
+
+
+int
+main(void)
+{
+	uint8_t fastpos[1 << FASTPOS_BITS];
+
+	const uint8_t fast_slots = 2 * FASTPOS_BITS;
+	uint32_t c = 2;
+
+	fastpos[0] = 0;
+	fastpos[1] = 1;
+
+	for (uint8_t slot_fast = 2; slot_fast < fast_slots; ++slot_fast) {
+		const uint32_t k = 1 << ((slot_fast >> 1) - 1);
+		for (uint32_t j = 0; j < k; ++j, ++c)
+			fastpos[c] = slot_fast;
+	}
+
+	printf("/* This file has been automatically generated "
+			"by fastpos_tablegen.c. */\n\n"
+			"#include \"common.h\"\n"
+			"#include \"fastpos.h\"\n\n"
+			"const uint8_t lzma_fastpos[1 << FASTPOS_BITS] = {");
+
+	for (size_t i = 0; i < (1 << FASTPOS_BITS); ++i) {
+		if (i % 16 == 0)
+			printf("\n\t");
+
+		printf("%3u", (unsigned int)(fastpos[i]));
+
+		if (i != (1 << FASTPOS_BITS) - 1)
+			printf(",");
+	}
+
+	printf("\n};\n");
+
+	return 0;
+}
diff --git a/Utilities/cmliblzma/liblzma/lzma/lzma2_decoder.c b/Utilities/cmliblzma/liblzma/lzma/lzma2_decoder.c
new file mode 100644
index 0000000..bd2a737
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/lzma/lzma2_decoder.c
@@ -0,0 +1,305 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       lzma2_decoder.c
+/// \brief      LZMA2 decoder
+///
+//  Authors:    Igor Pavlov
+//              Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "lzma2_decoder.h"
+#include "lz_decoder.h"
+#include "lzma_decoder.h"
+
+
+struct lzma_coder_s {
+	enum sequence {
+		SEQ_CONTROL,
+		SEQ_UNCOMPRESSED_1,
+		SEQ_UNCOMPRESSED_2,
+		SEQ_COMPRESSED_0,
+		SEQ_COMPRESSED_1,
+		SEQ_PROPERTIES,
+		SEQ_LZMA,
+		SEQ_COPY,
+	} sequence;
+
+	/// Sequence after the size fields have been decoded.
+	enum sequence next_sequence;
+
+	/// LZMA decoder
+	lzma_lz_decoder lzma;
+
+	/// Uncompressed size of LZMA chunk
+	size_t uncompressed_size;
+
+	/// Compressed size of the chunk (naturally equals to uncompressed
+	/// size of uncompressed chunk)
+	size_t compressed_size;
+
+	/// True if properties are needed. This is false before the
+	/// first LZMA chunk.
+	bool need_properties;
+
+	/// True if dictionary reset is needed. This is false before the
+	/// first chunk (LZMA or uncompressed).
+	bool need_dictionary_reset;
+
+	lzma_options_lzma options;
+};
+
+
+static lzma_ret
+lzma2_decode(lzma_coder *LZMA_RESTRICT coder, lzma_dict *LZMA_RESTRICT dict,
+		const uint8_t *LZMA_RESTRICT in, size_t *LZMA_RESTRICT in_pos,
+		size_t in_size)
+{
+	// With SEQ_LZMA it is possible that no new input is needed to do
+	// some progress. The rest of the sequences assume that there is
+	// at least one byte of input.
+	while (*in_pos < in_size || coder->sequence == SEQ_LZMA)
+	switch (coder->sequence) {
+	case SEQ_CONTROL: {
+		const uint32_t control = in[*in_pos];
+		++*in_pos;
+
+		// End marker
+		if (control == 0x00)
+			return LZMA_STREAM_END;
+
+		if (control >= 0xE0 || control == 1) {
+			// Dictionary reset implies that next LZMA chunk has
+			// to set new properties.
+			coder->need_properties = true;
+			coder->need_dictionary_reset = true;
+		} else if (coder->need_dictionary_reset) {
+			return LZMA_DATA_ERROR;
+		}
+
+		if (control >= 0x80) {
+			// LZMA chunk. The highest five bits of the
+			// uncompressed size are taken from the control byte.
+			coder->uncompressed_size = (control & 0x1F) << 16;
+			coder->sequence = SEQ_UNCOMPRESSED_1;
+
+			// See if there are new properties or if we need to
+			// reset the state.
+			if (control >= 0xC0) {
+				// When there are new properties, state reset
+				// is done at SEQ_PROPERTIES.
+				coder->need_properties = false;
+				coder->next_sequence = SEQ_PROPERTIES;
+
+			} else if (coder->need_properties) {
+				return LZMA_DATA_ERROR;
+
+			} else {
+				coder->next_sequence = SEQ_LZMA;
+
+				// If only state reset is wanted with old
+				// properties, do the resetting here for
+				// simplicity.
+				if (control >= 0xA0)
+					coder->lzma.reset(coder->lzma.coder,
+							&coder->options);
+			}
+		} else {
+			// Invalid control values
+			if (control > 2)
+				return LZMA_DATA_ERROR;
+
+			// It's uncompressed chunk
+			coder->sequence = SEQ_COMPRESSED_0;
+			coder->next_sequence = SEQ_COPY;
+		}
+
+		if (coder->need_dictionary_reset) {
+			// Finish the dictionary reset and let the caller
+			// flush the dictionary to the actual output buffer.
+			coder->need_dictionary_reset = false;
+			dict_reset(dict);
+			return LZMA_OK;
+		}
+
+		break;
+	}
+
+	case SEQ_UNCOMPRESSED_1:
+		coder->uncompressed_size += (uint32_t)(in[(*in_pos)++]) << 8;
+		coder->sequence = SEQ_UNCOMPRESSED_2;
+		break;
+
+	case SEQ_UNCOMPRESSED_2:
+		coder->uncompressed_size += in[(*in_pos)++] + 1;
+		coder->sequence = SEQ_COMPRESSED_0;
+		coder->lzma.set_uncompressed(coder->lzma.coder,
+				coder->uncompressed_size);
+		break;
+
+	case SEQ_COMPRESSED_0:
+		coder->compressed_size = (uint32_t)(in[(*in_pos)++]) << 8;
+		coder->sequence = SEQ_COMPRESSED_1;
+		break;
+
+	case SEQ_COMPRESSED_1:
+		coder->compressed_size += in[(*in_pos)++] + 1;
+		coder->sequence = coder->next_sequence;
+		break;
+
+	case SEQ_PROPERTIES:
+		if (lzma_lzma_lclppb_decode(&coder->options, in[(*in_pos)++]))
+			return LZMA_DATA_ERROR;
+
+		coder->lzma.reset(coder->lzma.coder, &coder->options);
+
+		coder->sequence = SEQ_LZMA;
+		break;
+
+	case SEQ_LZMA: {
+		// Store the start offset so that we can update
+		// coder->compressed_size later.
+		const size_t in_start = *in_pos;
+
+		// Decode from in[] to *dict.
+		const lzma_ret ret = coder->lzma.code(coder->lzma.coder,
+				dict, in, in_pos, in_size);
+
+		// Validate and update coder->compressed_size.
+		const size_t in_used = *in_pos - in_start;
+		if (in_used > coder->compressed_size)
+			return LZMA_DATA_ERROR;
+
+		coder->compressed_size -= in_used;
+
+		// Return if we didn't finish the chunk, or an error occurred.
+		if (ret != LZMA_STREAM_END)
+			return ret;
+
+		// The LZMA decoder must have consumed the whole chunk now.
+		// We don't need to worry about uncompressed size since it
+		// is checked by the LZMA decoder.
+		if (coder->compressed_size != 0)
+			return LZMA_DATA_ERROR;
+
+		coder->sequence = SEQ_CONTROL;
+		break;
+	}
+
+	case SEQ_COPY: {
+		// Copy from input to the dictionary as is.
+		dict_write(dict, in, in_pos, in_size, &coder->compressed_size);
+		if (coder->compressed_size != 0)
+			return LZMA_OK;
+
+		coder->sequence = SEQ_CONTROL;
+		break;
+	}
+
+	default:
+		assert(0);
+		return LZMA_PROG_ERROR;
+	}
+
+	return LZMA_OK;
+}
+
+
+static void
+lzma2_decoder_end(lzma_coder *coder, lzma_allocator *allocator)
+{
+	assert(coder->lzma.end == NULL);
+	lzma_free(coder->lzma.coder, allocator);
+
+	lzma_free(coder, allocator);
+
+	return;
+}
+
+
+static lzma_ret
+lzma2_decoder_init(lzma_lz_decoder *lz, lzma_allocator *allocator,
+		const void *opt, lzma_lz_options *lz_options)
+{
+	const lzma_options_lzma *options = opt;
+
+	if (lz->coder == NULL) {
+		lz->coder = lzma_alloc(sizeof(lzma_coder), allocator);
+		if (lz->coder == NULL)
+			return LZMA_MEM_ERROR;
+
+		lz->code = &lzma2_decode;
+		lz->end = &lzma2_decoder_end;
+
+		lz->coder->lzma = LZMA_LZ_DECODER_INIT;
+	}
+
+	lz->coder->sequence = SEQ_CONTROL;
+	lz->coder->need_properties = true;
+	lz->coder->need_dictionary_reset = options->preset_dict == NULL
+			|| options->preset_dict_size == 0;
+
+	return lzma_lzma_decoder_create(&lz->coder->lzma,
+			allocator, options, lz_options);
+}
+
+
+extern lzma_ret
+lzma_lzma2_decoder_init(lzma_next_coder *next, lzma_allocator *allocator,
+		const lzma_filter_info *filters)
+{
+	// LZMA2 can only be the last filter in the chain. This is enforced
+	// by the raw_decoder initialization.
+	assert(filters[1].init == NULL);
+
+	return lzma_lz_decoder_init(next, allocator, filters,
+			&lzma2_decoder_init);
+}
+
+
+extern uint64_t
+lzma_lzma2_decoder_memusage(const void *options)
+{
+	return sizeof(lzma_coder)
+			+ lzma_lzma_decoder_memusage_nocheck(options);
+}
+
+
+extern lzma_ret
+lzma_lzma2_props_decode(void **options, lzma_allocator *allocator,
+		const uint8_t *props, size_t props_size)
+{
+	lzma_options_lzma *opt;
+
+	if (props_size != 1)
+		return LZMA_OPTIONS_ERROR;
+
+	// Check that reserved bits are unset.
+	if (props[0] & 0xC0)
+		return LZMA_OPTIONS_ERROR;
+
+	// Decode the dictionary size.
+	if (props[0] > 40)
+		return LZMA_OPTIONS_ERROR;
+
+	opt = lzma_alloc(sizeof(lzma_options_lzma), allocator);
+	if (opt == NULL)
+		return LZMA_MEM_ERROR;
+
+	if (props[0] == 40) {
+		opt->dict_size = UINT32_MAX;
+	} else {
+		opt->dict_size = 2 | (props[0] & 1);
+		opt->dict_size <<= props[0] / 2 + 11;
+	}
+
+	opt->preset_dict = NULL;
+	opt->preset_dict_size = 0;
+
+	*options = opt;
+
+	return LZMA_OK;
+}
diff --git a/Utilities/cmliblzma/liblzma/lzma/lzma2_decoder.h b/Utilities/cmliblzma/liblzma/lzma/lzma2_decoder.h
new file mode 100644
index 0000000..fac4ac4
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/lzma/lzma2_decoder.h
@@ -0,0 +1,28 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       lzma2_decoder.h
+/// \brief      LZMA2 decoder
+///
+//  Authors:    Igor Pavlov
+//              Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#ifndef LZMA_LZMA2_DECODER_H
+#define LZMA_LZMA2_DECODER_H
+
+#include "common.h"
+
+extern lzma_ret lzma_lzma2_decoder_init(lzma_next_coder *next,
+		lzma_allocator *allocator, const lzma_filter_info *filters);
+
+extern uint64_t lzma_lzma2_decoder_memusage(const void *options);
+
+extern lzma_ret lzma_lzma2_props_decode(
+		void **options, lzma_allocator *allocator,
+		const uint8_t *props, size_t props_size);
+
+#endif
diff --git a/Utilities/cmliblzma/liblzma/lzma/lzma2_encoder.c b/Utilities/cmliblzma/liblzma/lzma/lzma2_encoder.c
new file mode 100644
index 0000000..a3651a7
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/lzma/lzma2_encoder.c
@@ -0,0 +1,399 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       lzma2_encoder.c
+/// \brief      LZMA2 encoder
+///
+//  Authors:    Igor Pavlov
+//              Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "lz_encoder.h"
+#include "lzma_encoder.h"
+#include "fastpos.h"
+#include "lzma2_encoder.h"
+
+
+struct lzma_coder_s {
+	enum {
+		SEQ_INIT,
+		SEQ_LZMA_ENCODE,
+		SEQ_LZMA_COPY,
+		SEQ_UNCOMPRESSED_HEADER,
+		SEQ_UNCOMPRESSED_COPY,
+	} sequence;
+
+	/// LZMA encoder
+	lzma_coder *lzma;
+
+	/// LZMA options currently in use.
+	lzma_options_lzma opt_cur;
+
+	bool need_properties;
+	bool need_state_reset;
+	bool need_dictionary_reset;
+
+	/// Uncompressed size of a chunk
+	size_t uncompressed_size;
+
+	/// Compressed size of a chunk (excluding headers); this is also used
+	/// to indicate the end of buf[] in SEQ_LZMA_COPY.
+	size_t compressed_size;
+
+	/// Read position in buf[]
+	size_t buf_pos;
+
+	/// Buffer to hold the chunk header and LZMA compressed data
+	uint8_t buf[LZMA2_HEADER_MAX + LZMA2_CHUNK_MAX];
+};
+
+
+static void
+lzma2_header_lzma(lzma_coder *coder)
+{
+	size_t pos;
+	size_t size;
+
+	assert(coder->uncompressed_size > 0);
+	assert(coder->uncompressed_size <= LZMA2_UNCOMPRESSED_MAX);
+	assert(coder->compressed_size > 0);
+	assert(coder->compressed_size <= LZMA2_CHUNK_MAX);
+
+	if (coder->need_properties) {
+		pos = 0;
+
+		if (coder->need_dictionary_reset)
+			coder->buf[pos] = 0x80 + (3 << 5);
+		else
+			coder->buf[pos] = 0x80 + (2 << 5);
+	} else {
+		pos = 1;
+
+		if (coder->need_state_reset)
+			coder->buf[pos] = 0x80 + (1 << 5);
+		else
+			coder->buf[pos] = 0x80;
+	}
+
+	// Set the start position for copying.
+	coder->buf_pos = pos;
+
+	// Uncompressed size
+	size = coder->uncompressed_size - 1;
+	coder->buf[pos++] += size >> 16;
+	coder->buf[pos++] = (size >> 8) & 0xFF;
+	coder->buf[pos++] = size & 0xFF;
+
+	// Compressed size
+	size = coder->compressed_size - 1;
+	coder->buf[pos++] = size >> 8;
+	coder->buf[pos++] = size & 0xFF;
+
+	// Properties, if needed
+	if (coder->need_properties)
+		lzma_lzma_lclppb_encode(&coder->opt_cur, coder->buf + pos);
+
+	coder->need_properties = false;
+	coder->need_state_reset = false;
+	coder->need_dictionary_reset = false;
+
+	// The copying code uses coder->compressed_size to indicate the end
+	// of coder->buf[], so we need add the maximum size of the header here.
+	coder->compressed_size += LZMA2_HEADER_MAX;
+
+	return;
+}
+
+
+static void
+lzma2_header_uncompressed(lzma_coder *coder)
+{
+	assert(coder->uncompressed_size > 0);
+	assert(coder->uncompressed_size <= LZMA2_CHUNK_MAX);
+
+	// If this is the first chunk, we need to include dictionary
+	// reset indicator.
+	if (coder->need_dictionary_reset)
+		coder->buf[0] = 1;
+	else
+		coder->buf[0] = 2;
+
+	coder->need_dictionary_reset = false;
+
+	// "Compressed" size
+	coder->buf[1] = (coder->uncompressed_size - 1) >> 8;
+	coder->buf[2] = (coder->uncompressed_size - 1) & 0xFF;
+
+	// Set the start position for copying.
+	coder->buf_pos = 0;
+	return;
+}
+
+
+static lzma_ret
+lzma2_encode(lzma_coder *LZMA_RESTRICT coder, lzma_mf *LZMA_RESTRICT mf,
+		uint8_t *LZMA_RESTRICT out, size_t *LZMA_RESTRICT out_pos,
+		size_t out_size)
+{
+	while (*out_pos < out_size)
+	switch (coder->sequence) {
+	case SEQ_INIT:
+		// If there's no input left and we are flushing or finishing,
+		// don't start a new chunk.
+		if (mf_unencoded(mf) == 0) {
+			// Write end of payload marker if finishing.
+			if (mf->action == LZMA_FINISH)
+				out[(*out_pos)++] = 0;
+
+			return mf->action == LZMA_RUN
+					? LZMA_OK : LZMA_STREAM_END;
+		}
+
+		if (coder->need_state_reset)
+			return_if_error(lzma_lzma_encoder_reset(
+					coder->lzma, &coder->opt_cur));
+
+		coder->uncompressed_size = 0;
+		coder->compressed_size = 0;
+		coder->sequence = SEQ_LZMA_ENCODE;
+
+	// Fall through
+
+	case SEQ_LZMA_ENCODE: {
+		uint32_t read_start;
+		lzma_ret ret;
+
+		// Calculate how much more uncompressed data this chunk
+		// could accept.
+		const uint32_t left = LZMA2_UNCOMPRESSED_MAX
+				- coder->uncompressed_size;
+		uint32_t limit;
+
+		if (left < mf->match_len_max) {
+			// Must flush immediately since the next LZMA symbol
+			// could make the uncompressed size of the chunk too
+			// big.
+			limit = 0;
+		} else {
+			// Calculate maximum read_limit that is OK from point
+			// of view of LZMA2 chunk size.
+			limit = mf->read_pos - mf->read_ahead
+					+ left - mf->match_len_max;
+		}
+
+		// Save the start position so that we can update
+		// coder->uncompressed_size.
+		read_start = mf->read_pos - mf->read_ahead;
+
+		// Call the LZMA encoder until the chunk is finished.
+		ret = lzma_lzma_encode(coder->lzma, mf,
+				coder->buf + LZMA2_HEADER_MAX,
+				&coder->compressed_size,
+				LZMA2_CHUNK_MAX, limit);
+
+		coder->uncompressed_size += mf->read_pos - mf->read_ahead
+				- read_start;
+
+		assert(coder->compressed_size <= LZMA2_CHUNK_MAX);
+		assert(coder->uncompressed_size <= LZMA2_UNCOMPRESSED_MAX);
+
+		if (ret != LZMA_STREAM_END)
+			return LZMA_OK;
+
+		// See if the chunk compressed. If it didn't, we encode it
+		// as uncompressed chunk. This saves a few bytes of space
+		// and makes decoding faster.
+		if (coder->compressed_size >= coder->uncompressed_size) {
+			coder->uncompressed_size += mf->read_ahead;
+			assert(coder->uncompressed_size
+					<= LZMA2_UNCOMPRESSED_MAX);
+			mf->read_ahead = 0;
+			lzma2_header_uncompressed(coder);
+			coder->need_state_reset = true;
+			coder->sequence = SEQ_UNCOMPRESSED_HEADER;
+			break;
+		}
+
+		// The chunk did compress at least by one byte, so we store
+		// the chunk as LZMA.
+		lzma2_header_lzma(coder);
+
+		coder->sequence = SEQ_LZMA_COPY;
+	}
+
+	// Fall through
+
+	case SEQ_LZMA_COPY:
+		// Copy the compressed chunk along its headers to the
+		// output buffer.
+		lzma_bufcpy(coder->buf, &coder->buf_pos,
+				coder->compressed_size,
+				out, out_pos, out_size);
+		if (coder->buf_pos != coder->compressed_size)
+			return LZMA_OK;
+
+		coder->sequence = SEQ_INIT;
+		break;
+
+	case SEQ_UNCOMPRESSED_HEADER:
+		// Copy the three-byte header to indicate uncompressed chunk.
+		lzma_bufcpy(coder->buf, &coder->buf_pos,
+				LZMA2_HEADER_UNCOMPRESSED,
+				out, out_pos, out_size);
+		if (coder->buf_pos != LZMA2_HEADER_UNCOMPRESSED)
+			return LZMA_OK;
+
+		coder->sequence = SEQ_UNCOMPRESSED_COPY;
+
+	// Fall through
+
+	case SEQ_UNCOMPRESSED_COPY:
+		// Copy the uncompressed data as is from the dictionary
+		// to the output buffer.
+		mf_read(mf, out, out_pos, out_size, &coder->uncompressed_size);
+		if (coder->uncompressed_size != 0)
+			return LZMA_OK;
+
+		coder->sequence = SEQ_INIT;
+		break;
+	}
+
+	return LZMA_OK;
+}
+
+
+static void
+lzma2_encoder_end(lzma_coder *coder, lzma_allocator *allocator)
+{
+	lzma_free(coder->lzma, allocator);
+	lzma_free(coder, allocator);
+	return;
+}
+
+
+static lzma_ret
+lzma2_encoder_options_update(lzma_coder *coder, const lzma_filter *filter)
+{
+	lzma_options_lzma *opt;
+
+	// New options can be set only when there is no incomplete chunk.
+	// This is the case at the beginning of the raw stream and right
+	// after LZMA_SYNC_FLUSH.
+	if (filter->options == NULL || coder->sequence != SEQ_INIT)
+		return LZMA_PROG_ERROR;
+
+	// Look if there are new options. At least for now,
+	// only lc/lp/pb can be changed.
+	opt = filter->options;
+	if (coder->opt_cur.lc != opt->lc || coder->opt_cur.lp != opt->lp
+			|| coder->opt_cur.pb != opt->pb) {
+		// Validate the options.
+		if (opt->lc > LZMA_LCLP_MAX || opt->lp > LZMA_LCLP_MAX
+				|| opt->lc + opt->lp > LZMA_LCLP_MAX
+				|| opt->pb > LZMA_PB_MAX)
+			return LZMA_OPTIONS_ERROR;
+
+		// The new options will be used when the encoder starts
+		// a new LZMA2 chunk.
+		coder->opt_cur.lc = opt->lc;
+		coder->opt_cur.lp = opt->lp;
+		coder->opt_cur.pb = opt->pb;
+		coder->need_properties = true;
+		coder->need_state_reset = true;
+	}
+
+	return LZMA_OK;
+}
+
+
+static lzma_ret
+lzma2_encoder_init(lzma_lz_encoder *lz, lzma_allocator *allocator,
+		const void *options, lzma_lz_options *lz_options)
+{
+	if (options == NULL)
+		return LZMA_PROG_ERROR;
+
+	if (lz->coder == NULL) {
+		lz->coder = lzma_alloc(sizeof(lzma_coder), allocator);
+		if (lz->coder == NULL)
+			return LZMA_MEM_ERROR;
+
+		lz->code = &lzma2_encode;
+		lz->end = &lzma2_encoder_end;
+		lz->options_update = &lzma2_encoder_options_update;
+
+		lz->coder->lzma = NULL;
+	}
+
+	lz->coder->opt_cur = *(const lzma_options_lzma *)(options);
+
+	lz->coder->sequence = SEQ_INIT;
+	lz->coder->need_properties = true;
+	lz->coder->need_state_reset = false;
+	lz->coder->need_dictionary_reset
+			= lz->coder->opt_cur.preset_dict == NULL
+			|| lz->coder->opt_cur.preset_dict_size == 0;
+
+	// Initialize LZMA encoder
+	return_if_error(lzma_lzma_encoder_create(&lz->coder->lzma, allocator,
+			&lz->coder->opt_cur, lz_options));
+
+	// Make sure that we will always have enough history available in
+	// case we need to use uncompressed chunks. They are used when the
+	// compressed size of a chunk is not smaller than the uncompressed
+	// size, so we need to have at least LZMA2_COMPRESSED_MAX bytes
+	// history available.
+	if (lz_options->before_size + lz_options->dict_size < LZMA2_CHUNK_MAX)
+		lz_options->before_size
+				= LZMA2_CHUNK_MAX - lz_options->dict_size;
+
+	return LZMA_OK;
+}
+
+
+extern lzma_ret
+lzma_lzma2_encoder_init(lzma_next_coder *next, lzma_allocator *allocator,
+		const lzma_filter_info *filters)
+{
+	return lzma_lz_encoder_init(
+			next, allocator, filters, &lzma2_encoder_init);
+}
+
+
+extern uint64_t
+lzma_lzma2_encoder_memusage(const void *options)
+{
+	const uint64_t lzma_mem = lzma_lzma_encoder_memusage(options);
+	if (lzma_mem == UINT64_MAX)
+		return UINT64_MAX;
+
+	return sizeof(lzma_coder) + lzma_mem;
+}
+
+
+extern lzma_ret
+lzma_lzma2_props_encode(const void *options, uint8_t *out)
+{
+	const lzma_options_lzma *const opt = options;
+	uint32_t d = my_max(opt->dict_size, LZMA_DICT_SIZE_MIN);
+
+	// Round up to the next 2^n - 1 or 2^n + 2^(n - 1) - 1 depending
+	// on which one is the next:
+	--d;
+	d |= d >> 2;
+	d |= d >> 3;
+	d |= d >> 4;
+	d |= d >> 8;
+	d |= d >> 16;
+
+	// Get the highest two bits using the proper encoding:
+	if (d == UINT32_MAX)
+		out[0] = 40;
+	else
+		out[0] = get_pos_slot(d + 1) - 24;
+
+	return LZMA_OK;
+}
diff --git a/Utilities/cmliblzma/liblzma/lzma/lzma2_encoder.h b/Utilities/cmliblzma/liblzma/lzma/lzma2_encoder.h
new file mode 100644
index 0000000..ca19ef4
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/lzma/lzma2_encoder.h
@@ -0,0 +1,41 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       lzma2_encoder.h
+/// \brief      LZMA2 encoder
+///
+//  Authors:    Igor Pavlov
+//              Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#ifndef LZMA_LZMA2_ENCODER_H
+#define LZMA_LZMA2_ENCODER_H
+
+#include "common.h"
+
+
+/// Maximum number of bytes of actual data per chunk (no headers)
+#define LZMA2_CHUNK_MAX (UINT32_C(1) << 16)
+
+/// Maximum uncompressed size of LZMA chunk (no headers)
+#define LZMA2_UNCOMPRESSED_MAX (UINT32_C(1) << 21)
+
+/// Maximum size of LZMA2 headers
+#define LZMA2_HEADER_MAX 6
+
+/// Size of a header for uncompressed chunk
+#define LZMA2_HEADER_UNCOMPRESSED 3
+
+
+extern lzma_ret lzma_lzma2_encoder_init(
+		lzma_next_coder *next, lzma_allocator *allocator,
+		const lzma_filter_info *filters);
+
+extern uint64_t lzma_lzma2_encoder_memusage(const void *options);
+
+extern lzma_ret lzma_lzma2_props_encode(const void *options, uint8_t *out);
+
+#endif
diff --git a/Utilities/cmliblzma/liblzma/lzma/lzma_common.h b/Utilities/cmliblzma/liblzma/lzma/lzma_common.h
new file mode 100644
index 0000000..36267dc
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/lzma/lzma_common.h
@@ -0,0 +1,226 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       lzma_common.h
+/// \brief      Private definitions common to LZMA encoder and decoder
+///
+//  Authors:    Igor Pavlov
+//              Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#ifndef LZMA_LZMA_COMMON_H
+#define LZMA_LZMA_COMMON_H
+
+#include "common.h"
+#include "range_common.h"
+
+
+///////////////////
+// Miscellaneous //
+///////////////////
+
+/// Maximum number of position states. A position state is the lowest pos bits
+/// number of bits of the current uncompressed offset. In some places there
+/// are different sets of probabilities for different pos states.
+#define POS_STATES_MAX (1 << LZMA_PB_MAX)
+
+
+/// Validates lc, lp, and pb.
+static inline bool
+is_lclppb_valid(const lzma_options_lzma *options)
+{
+	return options->lc <= LZMA_LCLP_MAX && options->lp <= LZMA_LCLP_MAX
+			&& options->lc + options->lp <= LZMA_LCLP_MAX
+			&& options->pb <= LZMA_PB_MAX;
+}
+
+
+///////////
+// State //
+///////////
+
+/// This enum is used to track which events have occurred most recently and
+/// in which order. This information is used to predict the next event.
+///
+/// Events:
+///  - Literal: One 8-bit byte
+///  - Match: Repeat a chunk of data at some distance
+///  - Long repeat: Multi-byte match at a recently seen distance
+///  - Short repeat: One-byte repeat at a recently seen distance
+///
+/// The event names are in from STATE_oldest_older_previous. REP means
+/// either short or long repeated match, and NONLIT means any non-literal.
+typedef enum {
+	STATE_LIT_LIT,
+	STATE_MATCH_LIT_LIT,
+	STATE_REP_LIT_LIT,
+	STATE_SHORTREP_LIT_LIT,
+	STATE_MATCH_LIT,
+	STATE_REP_LIT,
+	STATE_SHORTREP_LIT,
+	STATE_LIT_MATCH,
+	STATE_LIT_LONGREP,
+	STATE_LIT_SHORTREP,
+	STATE_NONLIT_MATCH,
+	STATE_NONLIT_REP,
+} lzma_lzma_state;
+
+
+/// Total number of states
+#define STATES 12
+
+/// The lowest 7 states indicate that the previous state was a literal.
+#define LIT_STATES 7
+
+
+/// Indicate that the latest state was a literal.
+#define update_literal(state) \
+	state = ((state) <= STATE_SHORTREP_LIT_LIT \
+			? STATE_LIT_LIT \
+			: ((state) <= STATE_LIT_SHORTREP \
+				? (state) - 3 \
+				: (state) - 6))
+
+/// Indicate that the latest state was a match.
+#define update_match(state) \
+	state = ((state) < LIT_STATES ? STATE_LIT_MATCH : STATE_NONLIT_MATCH)
+
+/// Indicate that the latest state was a long repeated match.
+#define update_long_rep(state) \
+	state = ((state) < LIT_STATES ? STATE_LIT_LONGREP : STATE_NONLIT_REP)
+
+/// Indicate that the latest state was a short match.
+#define update_short_rep(state) \
+	state = ((state) < LIT_STATES ? STATE_LIT_SHORTREP : STATE_NONLIT_REP)
+
+/// Test if the previous state was a literal.
+#define is_literal_state(state) \
+	((state) < LIT_STATES)
+
+
+/////////////
+// Literal //
+/////////////
+
+/// Each literal coder is divided in three sections:
+///   - 0x001-0x0FF: Without match byte
+///   - 0x101-0x1FF: With match byte; match bit is 0
+///   - 0x201-0x2FF: With match byte; match bit is 1
+///
+/// Match byte is used when the previous LZMA symbol was something else than
+/// a literal (that is, it was some kind of match).
+#define LITERAL_CODER_SIZE 0x300
+
+/// Maximum number of literal coders
+#define LITERAL_CODERS_MAX (1 << LZMA_LCLP_MAX)
+
+/// Locate the literal coder for the next literal byte. The choice depends on
+///   - the lowest literal_pos_bits bits of the position of the current
+///     byte; and
+///   - the highest literal_context_bits bits of the previous byte.
+#define literal_subcoder(probs, lc, lp_mask, pos, prev_byte) \
+	((probs)[(((pos) & lp_mask) << lc) + ((prev_byte) >> (8 - lc))])
+
+
+static inline void
+literal_init(probability (*probs)[LITERAL_CODER_SIZE],
+		uint32_t lc, uint32_t lp)
+{
+	uint32_t coders;
+	uint32_t i, j;
+
+	assert(lc + lp <= LZMA_LCLP_MAX);
+
+	coders = 1U << (lc + lp);
+
+	for (i = 0; i < coders; ++i)
+		for (j = 0; j < LITERAL_CODER_SIZE; ++j)
+			bit_reset(probs[i][j]);
+
+	return;
+}
+
+
+//////////////////
+// Match length //
+//////////////////
+
+// Minimum length of a match is two bytes.
+#define MATCH_LEN_MIN 2
+
+// Match length is encoded with 4, 5, or 10 bits.
+//
+// Length   Bits
+//  2-9      4 = Choice=0 + 3 bits
+// 10-17     5 = Choice=1 + Choice2=0 + 3 bits
+// 18-273   10 = Choice=1 + Choice2=1 + 8 bits
+#define LEN_LOW_BITS 3
+#define LEN_LOW_SYMBOLS (1 << LEN_LOW_BITS)
+#define LEN_MID_BITS 3
+#define LEN_MID_SYMBOLS (1 << LEN_MID_BITS)
+#define LEN_HIGH_BITS 8
+#define LEN_HIGH_SYMBOLS (1 << LEN_HIGH_BITS)
+#define LEN_SYMBOLS (LEN_LOW_SYMBOLS + LEN_MID_SYMBOLS + LEN_HIGH_SYMBOLS)
+
+// Maximum length of a match is 273 which is a result of the encoding
+// described above.
+#define MATCH_LEN_MAX (MATCH_LEN_MIN + LEN_SYMBOLS - 1)
+
+
+////////////////////
+// Match distance //
+////////////////////
+
+// Different set of probabilities is used for match distances that have very
+// short match length: Lengths of 2, 3, and 4 bytes have a separate set of
+// probabilities for each length. The matches with longer length use a shared
+// set of probabilities.
+#define LEN_TO_POS_STATES 4
+
+// Macro to get the index of the appropriate probability array.
+#define get_len_to_pos_state(len) \
+	((len) < LEN_TO_POS_STATES + MATCH_LEN_MIN \
+		? (len) - MATCH_LEN_MIN \
+		: LEN_TO_POS_STATES - 1)
+
+// The highest two bits of a match distance (pos slot) are encoded using six
+// bits. See fastpos.h for more explanation.
+#define POS_SLOT_BITS 6
+#define POS_SLOTS (1 << POS_SLOT_BITS)
+
+// Match distances up to 127 are fully encoded using probabilities. Since
+// the highest two bits (pos slot) are always encoded using six bits, the
+// distances 0-3 don't need any additional bits to encode, since the pos
+// slot itself is the same as the actual distance. START_POS_MODEL_INDEX
+// indicates the first pos slot where at least one additional bit is needed.
+#define START_POS_MODEL_INDEX 4
+
+// Match distances greater than 127 are encoded in three pieces:
+//   - pos slot: the highest two bits
+//   - direct bits: 2-26 bits below the highest two bits
+//   - alignment bits: four lowest bits
+//
+// Direct bits don't use any probabilities.
+//
+// The pos slot value of 14 is for distances 128-191 (see the table in
+// fastpos.h to understand why).
+#define END_POS_MODEL_INDEX 14
+
+// Pos slots that indicate a distance <= 127.
+#define FULL_DISTANCES_BITS (END_POS_MODEL_INDEX / 2)
+#define FULL_DISTANCES (1 << FULL_DISTANCES_BITS)
+
+// For match distances greater than 127, only the highest two bits and the
+// lowest four bits (alignment) is encoded using probabilities.
+#define ALIGN_BITS 4
+#define ALIGN_TABLE_SIZE (1 << ALIGN_BITS)
+#define ALIGN_MASK (ALIGN_TABLE_SIZE - 1)
+
+// LZMA remembers the four most recent match distances. Reusing these distances
+// tends to take less space than re-encoding the actual distance value.
+#define REP_DISTANCES 4
+
+#endif
diff --git a/Utilities/cmliblzma/liblzma/lzma/lzma_decoder.c b/Utilities/cmliblzma/liblzma/lzma/lzma_decoder.c
new file mode 100644
index 0000000..3c0f393
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/lzma/lzma_decoder.c
@@ -0,0 +1,1075 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       lzma_decoder.c
+/// \brief      LZMA decoder
+///
+//  Authors:    Igor Pavlov
+//              Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "lz_decoder.h"
+#include "lzma_common.h"
+#include "lzma_decoder.h"
+#include "range_decoder.h"
+
+
+#ifdef HAVE_SMALL
+
+// Macros for (somewhat) size-optimized code.
+#define seq_4(seq) seq
+
+#define seq_6(seq) seq
+
+#define seq_8(seq) seq
+
+#define seq_len(seq) \
+	seq ## _CHOICE, \
+	seq ## _CHOICE2, \
+	seq ## _BITTREE
+
+#define len_decode(target, ld, pos_state, seq) \
+do { \
+case seq ## _CHOICE: \
+	rc_if_0(ld.choice, seq ## _CHOICE) { \
+		rc_update_0(ld.choice); \
+		probs = ld.low[pos_state];\
+		limit = LEN_LOW_SYMBOLS; \
+		target = MATCH_LEN_MIN; \
+	} else { \
+		rc_update_1(ld.choice); \
+case seq ## _CHOICE2: \
+		rc_if_0(ld.choice2, seq ## _CHOICE2) { \
+			rc_update_0(ld.choice2); \
+			probs = ld.mid[pos_state]; \
+			limit = LEN_MID_SYMBOLS; \
+			target = MATCH_LEN_MIN + LEN_LOW_SYMBOLS; \
+		} else { \
+			rc_update_1(ld.choice2); \
+			probs = ld.high; \
+			limit = LEN_HIGH_SYMBOLS; \
+			target = MATCH_LEN_MIN + LEN_LOW_SYMBOLS \
+					+ LEN_MID_SYMBOLS; \
+		} \
+	} \
+	symbol = 1; \
+case seq ## _BITTREE: \
+	do { \
+		rc_bit(probs[symbol], , , seq ## _BITTREE); \
+	} while (symbol < limit); \
+	target += symbol - limit; \
+} while (0)
+
+#else // HAVE_SMALL
+
+// Unrolled versions
+#define seq_4(seq) \
+	seq ## 0, \
+	seq ## 1, \
+	seq ## 2, \
+	seq ## 3
+
+#define seq_6(seq) \
+	seq ## 0, \
+	seq ## 1, \
+	seq ## 2, \
+	seq ## 3, \
+	seq ## 4, \
+	seq ## 5
+
+#define seq_8(seq) \
+	seq ## 0, \
+	seq ## 1, \
+	seq ## 2, \
+	seq ## 3, \
+	seq ## 4, \
+	seq ## 5, \
+	seq ## 6, \
+	seq ## 7
+
+#define seq_len(seq) \
+	seq ## _CHOICE, \
+	seq ## _LOW0, \
+	seq ## _LOW1, \
+	seq ## _LOW2, \
+	seq ## _CHOICE2, \
+	seq ## _MID0, \
+	seq ## _MID1, \
+	seq ## _MID2, \
+	seq ## _HIGH0, \
+	seq ## _HIGH1, \
+	seq ## _HIGH2, \
+	seq ## _HIGH3, \
+	seq ## _HIGH4, \
+	seq ## _HIGH5, \
+	seq ## _HIGH6, \
+	seq ## _HIGH7
+
+#define len_decode(target, ld, pos_state, seq) \
+do { \
+	symbol = 1; \
+case seq ## _CHOICE: \
+	rc_if_0(ld.choice, seq ## _CHOICE) { \
+		rc_update_0(ld.choice); \
+		rc_bit_case(ld.low[pos_state][symbol], 0, 0, seq ## _LOW0); \
+		rc_bit_case(ld.low[pos_state][symbol], 0, 0, seq ## _LOW1); \
+		rc_bit_case(ld.low[pos_state][symbol], 0, 0, seq ## _LOW2); \
+		target = symbol - LEN_LOW_SYMBOLS + MATCH_LEN_MIN; \
+	} else { \
+		rc_update_1(ld.choice); \
+case seq ## _CHOICE2: \
+		rc_if_0(ld.choice2, seq ## _CHOICE2) { \
+			rc_update_0(ld.choice2); \
+			rc_bit_case(ld.mid[pos_state][symbol], 0, 0, \
+					seq ## _MID0); \
+			rc_bit_case(ld.mid[pos_state][symbol], 0, 0, \
+					seq ## _MID1); \
+			rc_bit_case(ld.mid[pos_state][symbol], 0, 0, \
+					seq ## _MID2); \
+			target = symbol - LEN_MID_SYMBOLS \
+					+ MATCH_LEN_MIN + LEN_LOW_SYMBOLS; \
+		} else { \
+			rc_update_1(ld.choice2); \
+			rc_bit_case(ld.high[symbol], 0, 0, seq ## _HIGH0); \
+			rc_bit_case(ld.high[symbol], 0, 0, seq ## _HIGH1); \
+			rc_bit_case(ld.high[symbol], 0, 0, seq ## _HIGH2); \
+			rc_bit_case(ld.high[symbol], 0, 0, seq ## _HIGH3); \
+			rc_bit_case(ld.high[symbol], 0, 0, seq ## _HIGH4); \
+			rc_bit_case(ld.high[symbol], 0, 0, seq ## _HIGH5); \
+			rc_bit_case(ld.high[symbol], 0, 0, seq ## _HIGH6); \
+			rc_bit_case(ld.high[symbol], 0, 0, seq ## _HIGH7); \
+			target = symbol - LEN_HIGH_SYMBOLS \
+					+ MATCH_LEN_MIN \
+					+ LEN_LOW_SYMBOLS + LEN_MID_SYMBOLS; \
+		} \
+	} \
+} while (0)
+
+#endif // HAVE_SMALL
+
+
+/// Length decoder probabilities; see comments in lzma_common.h.
+typedef struct {
+	probability choice;
+	probability choice2;
+	probability low[POS_STATES_MAX][LEN_LOW_SYMBOLS];
+	probability mid[POS_STATES_MAX][LEN_MID_SYMBOLS];
+	probability high[LEN_HIGH_SYMBOLS];
+} lzma_length_decoder;
+
+
+struct lzma_coder_s {
+	///////////////////
+	// Probabilities //
+	///////////////////
+
+	/// Literals; see comments in lzma_common.h.
+	probability literal[LITERAL_CODERS_MAX][LITERAL_CODER_SIZE];
+
+	/// If 1, it's a match. Otherwise it's a single 8-bit literal.
+	probability is_match[STATES][POS_STATES_MAX];
+
+	/// If 1, it's a repeated match. The distance is one of rep0 .. rep3.
+	probability is_rep[STATES];
+
+	/// If 0, distance of a repeated match is rep0.
+	/// Otherwise check is_rep1.
+	probability is_rep0[STATES];
+
+	/// If 0, distance of a repeated match is rep1.
+	/// Otherwise check is_rep2.
+	probability is_rep1[STATES];
+
+	/// If 0, distance of a repeated match is rep2. Otherwise it is rep3.
+	probability is_rep2[STATES];
+
+	/// If 1, the repeated match has length of one byte. Otherwise
+	/// the length is decoded from rep_len_decoder.
+	probability is_rep0_long[STATES][POS_STATES_MAX];
+
+	/// Probability tree for the highest two bits of the match distance.
+	/// There is a separate probability tree for match lengths of
+	/// 2 (i.e. MATCH_LEN_MIN), 3, 4, and [5, 273].
+	probability pos_slot[LEN_TO_POS_STATES][POS_SLOTS];
+
+	/// Probability trees for additional bits for match distance when the
+	/// distance is in the range [4, 127].
+	probability pos_special[FULL_DISTANCES - END_POS_MODEL_INDEX];
+
+	/// Probability tree for the lowest four bits of a match distance
+	/// that is equal to or greater than 128.
+	probability pos_align[ALIGN_TABLE_SIZE];
+
+	/// Length of a normal match
+	lzma_length_decoder match_len_decoder;
+
+	/// Length of a repeated match
+	lzma_length_decoder rep_len_decoder;
+
+	///////////////////
+	// Decoder state //
+	///////////////////
+
+	// Range coder
+	lzma_range_decoder rc;
+
+	// Types of the most recently seen LZMA symbols
+	lzma_lzma_state state;
+
+	uint32_t rep0;      ///< Distance of the latest match
+	uint32_t rep1;      ///< Distance of second latest match
+	uint32_t rep2;      ///< Distance of third latest match
+	uint32_t rep3;      ///< Distance of fourth latest match
+
+	uint32_t pos_mask; // (1U << pb) - 1
+	uint32_t literal_context_bits;
+	uint32_t literal_pos_mask;
+
+	/// Uncompressed size as bytes, or LZMA_VLI_UNKNOWN if end of
+	/// payload marker is expected.
+	lzma_vli uncompressed_size;
+
+	////////////////////////////////
+	// State of incomplete symbol //
+	////////////////////////////////
+
+	/// Position where to continue the decoder loop
+	enum {
+		SEQ_NORMALIZE,
+		SEQ_IS_MATCH,
+		seq_8(SEQ_LITERAL),
+		seq_8(SEQ_LITERAL_MATCHED),
+		SEQ_LITERAL_WRITE,
+		SEQ_IS_REP,
+		seq_len(SEQ_MATCH_LEN),
+		seq_6(SEQ_POS_SLOT),
+		SEQ_POS_MODEL,
+		SEQ_DIRECT,
+		seq_4(SEQ_ALIGN),
+		SEQ_EOPM,
+		SEQ_IS_REP0,
+		SEQ_SHORTREP,
+		SEQ_IS_REP0_LONG,
+		SEQ_IS_REP1,
+		SEQ_IS_REP2,
+		seq_len(SEQ_REP_LEN),
+		SEQ_COPY,
+	} sequence;
+
+	/// Base of the current probability tree
+	probability *probs;
+
+	/// Symbol being decoded. This is also used as an index variable in
+	/// bittree decoders: probs[symbol]
+	uint32_t symbol;
+
+	/// Used as a loop termination condition on bittree decoders and
+	/// direct bits decoder.
+	uint32_t limit;
+
+	/// Matched literal decoder: 0x100 or 0 to help avoiding branches.
+	/// Bittree reverse decoders: Offset of the next bit: 1 << offset
+	uint32_t offset;
+
+	/// If decoding a literal: match byte.
+	/// If decoding a match: length of the match.
+	uint32_t len;
+};
+
+
+static lzma_ret
+lzma_decode(lzma_coder *LZMA_RESTRICT coder, lzma_dict *LZMA_RESTRICT dictptr,
+		const uint8_t *LZMA_RESTRICT in,
+		size_t *LZMA_RESTRICT in_pos, size_t in_size)
+{
+	///////////////
+	// Variables //
+	///////////////
+
+	// Making local copies of often-used variables improves both
+	// speed and readability.
+
+	lzma_dict dict = *dictptr;
+
+	const size_t dict_start = dict.pos;
+
+	// Range decoder
+	rc_to_local(coder->rc, *in_pos);
+
+	// State
+	uint32_t state = coder->state;
+	uint32_t rep0 = coder->rep0;
+	uint32_t rep1 = coder->rep1;
+	uint32_t rep2 = coder->rep2;
+	uint32_t rep3 = coder->rep3;
+
+	const uint32_t pos_mask = coder->pos_mask;
+
+	// These variables are actually needed only if we last time ran
+	// out of input in the middle of the decoder loop.
+	probability *probs = coder->probs;
+	uint32_t symbol = coder->symbol;
+	uint32_t limit = coder->limit;
+	uint32_t offset = coder->offset;
+	uint32_t len = coder->len;
+
+	const uint32_t literal_pos_mask = coder->literal_pos_mask;
+	const uint32_t literal_context_bits = coder->literal_context_bits;
+
+	// Temporary variables
+	uint32_t pos_state = dict.pos & pos_mask;
+
+	lzma_ret ret = LZMA_OK;
+
+	// If uncompressed size is known, there must be no end of payload
+	// marker.
+	const bool no_eopm = coder->uncompressed_size
+			!= LZMA_VLI_UNKNOWN;
+	if (no_eopm && coder->uncompressed_size < dict.limit - dict.pos)
+		dict.limit = dict.pos + (size_t)(coder->uncompressed_size);
+
+	////////////////////
+	// Initialization //
+	////////////////////
+
+	if (!rc_read_init(&coder->rc, in, in_pos, in_size))
+		return LZMA_OK;
+
+	rc = coder->rc;
+	rc_in_pos = *in_pos;
+
+	// The main decoder loop. The "switch" is used to restart the decoder at
+	// correct location. Once restarted, the "switch" is no longer used.
+	switch (coder->sequence)
+	while (true) {
+		// Calculate new pos_state. This is skipped on the first loop
+		// since we already calculated it when setting up the local
+		// variables.
+		pos_state = dict.pos & pos_mask;
+
+	case SEQ_NORMALIZE:
+	case SEQ_IS_MATCH:
+		if (unlikely(no_eopm && dict.pos == dict.limit))
+			break;
+
+		rc_if_0(coder->is_match[state][pos_state], SEQ_IS_MATCH) {
+			static const lzma_lzma_state next_state[] = {
+				STATE_LIT_LIT,
+				STATE_LIT_LIT,
+				STATE_LIT_LIT,
+				STATE_LIT_LIT,
+				STATE_MATCH_LIT_LIT,
+				STATE_REP_LIT_LIT,
+				STATE_SHORTREP_LIT_LIT,
+				STATE_MATCH_LIT,
+				STATE_REP_LIT,
+				STATE_SHORTREP_LIT,
+				STATE_MATCH_LIT,
+				STATE_REP_LIT
+			};
+
+			rc_update_0(coder->is_match[state][pos_state]);
+
+			// It's a literal i.e. a single 8-bit byte.
+
+			probs = literal_subcoder(coder->literal,
+					literal_context_bits, literal_pos_mask,
+					dict.pos, dict_get(&dict, 0));
+			symbol = 1;
+
+			if (is_literal_state(state)) {
+				// Decode literal without match byte.
+#ifdef HAVE_SMALL
+	case SEQ_LITERAL:
+				do {
+					rc_bit(probs[symbol], , , SEQ_LITERAL);
+				} while (symbol < (1 << 8));
+#else
+				rc_bit_case(probs[symbol], 0, 0, SEQ_LITERAL0);
+				rc_bit_case(probs[symbol], 0, 0, SEQ_LITERAL1);
+				rc_bit_case(probs[symbol], 0, 0, SEQ_LITERAL2);
+				rc_bit_case(probs[symbol], 0, 0, SEQ_LITERAL3);
+				rc_bit_case(probs[symbol], 0, 0, SEQ_LITERAL4);
+				rc_bit_case(probs[symbol], 0, 0, SEQ_LITERAL5);
+				rc_bit_case(probs[symbol], 0, 0, SEQ_LITERAL6);
+				rc_bit_case(probs[symbol], 0, 0, SEQ_LITERAL7);
+#endif
+			} else {
+#ifndef HAVE_SMALL
+				uint32_t match_bit;
+				uint32_t subcoder_index;
+#endif
+
+				// Decode literal with match byte.
+				//
+				// We store the byte we compare against
+				// ("match byte") to "len" to minimize the
+				// number of variables we need to store
+				// between decoder calls.
+				len = dict_get(&dict, rep0) << 1;
+
+				// The usage of "offset" allows omitting some
+				// branches, which should give tiny speed
+				// improvement on some CPUs. "offset" gets
+				// set to zero if match_bit didn't match.
+				offset = 0x100;
+
+#ifdef HAVE_SMALL
+	case SEQ_LITERAL_MATCHED:
+				do {
+					const uint32_t match_bit
+							= len & offset;
+					const uint32_t subcoder_index
+							= offset + match_bit
+							+ symbol;
+
+					rc_bit(probs[subcoder_index],
+							offset &= ~match_bit,
+							offset &= match_bit,
+							SEQ_LITERAL_MATCHED);
+
+					// It seems to be faster to do this
+					// here instead of putting it to the
+					// beginning of the loop and then
+					// putting the "case" in the middle
+					// of the loop.
+					len <<= 1;
+
+				} while (symbol < (1 << 8));
+#else
+				// Unroll the loop.
+
+#	define d(seq) \
+		case seq: \
+			match_bit = len & offset; \
+			subcoder_index = offset + match_bit + symbol; \
+			rc_bit(probs[subcoder_index], \
+					offset &= ~match_bit, \
+					offset &= match_bit, \
+					seq)
+
+				d(SEQ_LITERAL_MATCHED0);
+				len <<= 1;
+				d(SEQ_LITERAL_MATCHED1);
+				len <<= 1;
+				d(SEQ_LITERAL_MATCHED2);
+				len <<= 1;
+				d(SEQ_LITERAL_MATCHED3);
+				len <<= 1;
+				d(SEQ_LITERAL_MATCHED4);
+				len <<= 1;
+				d(SEQ_LITERAL_MATCHED5);
+				len <<= 1;
+				d(SEQ_LITERAL_MATCHED6);
+				len <<= 1;
+				d(SEQ_LITERAL_MATCHED7);
+#	undef d
+#endif
+			}
+
+			//update_literal(state);
+			// Use a lookup table to update to literal state,
+			// since compared to other state updates, this would
+			// need two branches.
+			state = next_state[state];
+
+	case SEQ_LITERAL_WRITE:
+			if (unlikely(dict_put(&dict, symbol))) {
+				coder->sequence = SEQ_LITERAL_WRITE;
+				goto out;
+			}
+
+			continue;
+		}
+
+		// Instead of a new byte we are going to get a byte range
+		// (distance and length) which will be repeated from our
+		// output history.
+
+		rc_update_1(coder->is_match[state][pos_state]);
+
+	case SEQ_IS_REP:
+		rc_if_0(coder->is_rep[state], SEQ_IS_REP) {
+			// Not a repeated match
+			rc_update_0(coder->is_rep[state]);
+			update_match(state);
+
+			// The latest three match distances are kept in
+			// memory in case there are repeated matches.
+			rep3 = rep2;
+			rep2 = rep1;
+			rep1 = rep0;
+
+			// Decode the length of the match.
+			len_decode(len, coder->match_len_decoder,
+					pos_state, SEQ_MATCH_LEN);
+
+			// Prepare to decode the highest two bits of the
+			// match distance.
+			probs = coder->pos_slot[get_len_to_pos_state(len)];
+			symbol = 1;
+
+#ifdef HAVE_SMALL
+	case SEQ_POS_SLOT:
+			do {
+				rc_bit(probs[symbol], , , SEQ_POS_SLOT);
+			} while (symbol < POS_SLOTS);
+#else
+			rc_bit_case(probs[symbol], 0, 0, SEQ_POS_SLOT0);
+			rc_bit_case(probs[symbol], 0, 0, SEQ_POS_SLOT1);
+			rc_bit_case(probs[symbol], 0, 0, SEQ_POS_SLOT2);
+			rc_bit_case(probs[symbol], 0, 0, SEQ_POS_SLOT3);
+			rc_bit_case(probs[symbol], 0, 0, SEQ_POS_SLOT4);
+			rc_bit_case(probs[symbol], 0, 0, SEQ_POS_SLOT5);
+#endif
+			// Get rid of the highest bit that was needed for
+			// indexing of the probability array.
+			symbol -= POS_SLOTS;
+			assert(symbol <= 63);
+
+			if (symbol < START_POS_MODEL_INDEX) {
+				// Match distances [0, 3] have only two bits.
+				rep0 = symbol;
+			} else {
+				// Decode the lowest [1, 29] bits of
+				// the match distance.
+				limit = (symbol >> 1) - 1;
+				assert(limit >= 1 && limit <= 30);
+				rep0 = 2 + (symbol & 1);
+
+				if (symbol < END_POS_MODEL_INDEX) {
+					// Prepare to decode the low bits for
+					// a distance of [4, 127].
+					assert(limit <= 5);
+					rep0 <<= limit;
+					assert(rep0 <= 96);
+					// -1 is fine, because we start
+					// decoding at probs[1], not probs[0].
+					// NOTE: This violates the C standard,
+					// since we are doing pointer
+					// arithmetic past the beginning of
+					// the array.
+					assert((int32_t)(rep0 - symbol - 1)
+							>= -1);
+					assert((int32_t)(rep0 - symbol - 1)
+							<= 82);
+					probs = coder->pos_special + rep0
+							- symbol - 1;
+					symbol = 1;
+					offset = 0;
+	case SEQ_POS_MODEL:
+#ifdef HAVE_SMALL
+					do {
+						rc_bit(probs[symbol], ,
+							rep0 += 1 << offset,
+							SEQ_POS_MODEL);
+					} while (++offset < limit);
+#else
+					switch (limit) {
+					case 5:
+						assert(offset == 0);
+						rc_bit(probs[symbol], 0,
+							rep0 += 1,
+							SEQ_POS_MODEL);
+						++offset;
+						--limit;
+					case 4:
+						rc_bit(probs[symbol], 0,
+							rep0 += 1 << offset,
+							SEQ_POS_MODEL);
+						++offset;
+						--limit;
+					case 3:
+						rc_bit(probs[symbol], 0,
+							rep0 += 1 << offset,
+							SEQ_POS_MODEL);
+						++offset;
+						--limit;
+					case 2:
+						rc_bit(probs[symbol], 0,
+							rep0 += 1 << offset,
+							SEQ_POS_MODEL);
+						++offset;
+						--limit;
+					case 1:
+						// We need "symbol" only for
+						// indexing the probability
+						// array, thus we can use
+						// rc_bit_last() here to omit
+						// the unneeded updating of
+						// "symbol".
+						rc_bit_last(probs[symbol], 0,
+							rep0 += 1 << offset,
+							SEQ_POS_MODEL);
+					}
+#endif
+				} else {
+					// The distance is >= 128. Decode the
+					// lower bits without probabilities
+					// except the lowest four bits.
+					assert(symbol >= 14);
+					assert(limit >= 6);
+					limit -= ALIGN_BITS;
+					assert(limit >= 2);
+	case SEQ_DIRECT:
+					// Not worth manual unrolling
+					do {
+						rc_direct(rep0, SEQ_DIRECT);
+					} while (--limit > 0);
+
+					// Decode the lowest four bits using
+					// probabilities.
+					rep0 <<= ALIGN_BITS;
+					symbol = 1;
+#ifdef HAVE_SMALL
+					offset = 0;
+	case SEQ_ALIGN:
+					do {
+						rc_bit(coder->pos_align[
+								symbol], ,
+							rep0 += 1 << offset,
+							SEQ_ALIGN);
+					} while (++offset < ALIGN_BITS);
+#else
+	case SEQ_ALIGN0:
+					rc_bit(coder->pos_align[symbol], 0,
+							rep0 += 1, SEQ_ALIGN0);
+	case SEQ_ALIGN1:
+					rc_bit(coder->pos_align[symbol], 0,
+							rep0 += 2, SEQ_ALIGN1);
+	case SEQ_ALIGN2:
+					rc_bit(coder->pos_align[symbol], 0,
+							rep0 += 4, SEQ_ALIGN2);
+	case SEQ_ALIGN3:
+					// Like in SEQ_POS_MODEL, we don't
+					// need "symbol" for anything else
+					// than indexing the probability array.
+					rc_bit_last(coder->pos_align[symbol], 0,
+							rep0 += 8, SEQ_ALIGN3);
+#endif
+
+					if (rep0 == UINT32_MAX) {
+						// End of payload marker was
+						// found. It must not be
+						// present if uncompressed
+						// size is known.
+						if (coder->uncompressed_size
+						!= LZMA_VLI_UNKNOWN) {
+							ret = LZMA_DATA_ERROR;
+							goto out;
+						}
+
+	case SEQ_EOPM:
+						// LZMA1 stream with
+						// end-of-payload marker.
+						rc_normalize(SEQ_EOPM);
+						ret = LZMA_STREAM_END;
+						goto out;
+					}
+				}
+			}
+
+			// Validate the distance we just decoded.
+			if (unlikely(!dict_is_distance_valid(&dict, rep0))) {
+				ret = LZMA_DATA_ERROR;
+				goto out;
+			}
+
+		} else {
+			rc_update_1(coder->is_rep[state]);
+
+			// Repeated match
+			//
+			// The match distance is a value that we have had
+			// earlier. The latest four match distances are
+			// available as rep0, rep1, rep2 and rep3. We will
+			// now decode which of them is the new distance.
+			//
+			// There cannot be a match if we haven't produced
+			// any output, so check that first.
+			if (unlikely(!dict_is_distance_valid(&dict, 0))) {
+				ret = LZMA_DATA_ERROR;
+				goto out;
+			}
+
+	case SEQ_IS_REP0:
+			rc_if_0(coder->is_rep0[state], SEQ_IS_REP0) {
+				rc_update_0(coder->is_rep0[state]);
+				// The distance is rep0.
+
+	case SEQ_IS_REP0_LONG:
+				rc_if_0(coder->is_rep0_long[state][pos_state],
+						SEQ_IS_REP0_LONG) {
+					rc_update_0(coder->is_rep0_long[
+							state][pos_state]);
+
+					update_short_rep(state);
+
+	case SEQ_SHORTREP:
+					if (unlikely(dict_put(&dict, dict_get(
+							&dict, rep0)))) {
+						coder->sequence = SEQ_SHORTREP;
+						goto out;
+					}
+
+					continue;
+				}
+
+				// Repeating more than one byte at
+				// distance of rep0.
+				rc_update_1(coder->is_rep0_long[
+						state][pos_state]);
+
+			} else {
+				rc_update_1(coder->is_rep0[state]);
+
+	case SEQ_IS_REP1:
+				// The distance is rep1, rep2 or rep3. Once
+				// we find out which one of these three, it
+				// is stored to rep0 and rep1, rep2 and rep3
+				// are updated accordingly.
+				rc_if_0(coder->is_rep1[state], SEQ_IS_REP1) {
+					uint32_t distance;
+
+					rc_update_0(coder->is_rep1[state]);
+
+					distance = rep1;
+					rep1 = rep0;
+					rep0 = distance;
+
+				} else {
+					rc_update_1(coder->is_rep1[state]);
+	case SEQ_IS_REP2:
+					rc_if_0(coder->is_rep2[state],
+							SEQ_IS_REP2) {
+						uint32_t distance;
+
+						rc_update_0(coder->is_rep2[
+								state]);
+
+						distance = rep2;
+						rep2 = rep1;
+						rep1 = rep0;
+						rep0 = distance;
+
+					} else {
+						uint32_t distance;
+
+						rc_update_1(coder->is_rep2[
+								state]);
+
+						distance = rep3;
+						rep3 = rep2;
+						rep2 = rep1;
+						rep1 = rep0;
+						rep0 = distance;
+					}
+				}
+			}
+
+			update_long_rep(state);
+
+			// Decode the length of the repeated match.
+			len_decode(len, coder->rep_len_decoder,
+					pos_state, SEQ_REP_LEN);
+		}
+
+		/////////////////////////////////
+		// Repeat from history buffer. //
+		/////////////////////////////////
+
+		// The length is always between these limits. There is no way
+		// to trigger the algorithm to set len outside this range.
+		assert(len >= MATCH_LEN_MIN);
+		assert(len <= MATCH_LEN_MAX);
+
+	case SEQ_COPY:
+		// Repeat len bytes from distance of rep0.
+		if (unlikely(dict_repeat(&dict, rep0, &len))) {
+			coder->sequence = SEQ_COPY;
+			goto out;
+		}
+	}
+
+	rc_normalize(SEQ_NORMALIZE);
+	coder->sequence = SEQ_IS_MATCH;
+
+out:
+	// Save state
+
+	// NOTE: Must not copy dict.limit.
+	dictptr->pos = dict.pos;
+	dictptr->full = dict.full;
+
+	rc_from_local(coder->rc, *in_pos);
+
+	coder->state = state;
+	coder->rep0 = rep0;
+	coder->rep1 = rep1;
+	coder->rep2 = rep2;
+	coder->rep3 = rep3;
+
+	coder->probs = probs;
+	coder->symbol = symbol;
+	coder->limit = limit;
+	coder->offset = offset;
+	coder->len = len;
+
+	// Update the remaining amount of uncompressed data if uncompressed
+	// size was known.
+	if (coder->uncompressed_size != LZMA_VLI_UNKNOWN) {
+		coder->uncompressed_size -= dict.pos - dict_start;
+
+		// Since there cannot be end of payload marker if the
+		// uncompressed size was known, we check here if we
+		// finished decoding.
+		if (coder->uncompressed_size == 0 && ret == LZMA_OK
+				&& coder->sequence != SEQ_NORMALIZE)
+			ret = coder->sequence == SEQ_IS_MATCH
+					? LZMA_STREAM_END : LZMA_DATA_ERROR;
+	}
+
+	// We can do an additional check in the range decoder to catch some
+	// corrupted files.
+	if (ret == LZMA_STREAM_END) {
+		if (!rc_is_finished(coder->rc))
+			ret = LZMA_DATA_ERROR;
+
+		// Reset the range decoder so that it is ready to reinitialize
+		// for a new LZMA2 chunk.
+		rc_reset(coder->rc);
+	}
+
+	return ret;
+}
+
+
+
+static void
+lzma_decoder_uncompressed(lzma_coder *coder, lzma_vli uncompressed_size)
+{
+	coder->uncompressed_size = uncompressed_size;
+}
+
+/*
+extern void
+lzma_lzma_decoder_uncompressed(void *coder_ptr, lzma_vli uncompressed_size)
+{
+	// This is hack.
+	(*(lzma_coder **)(coder))->uncompressed_size = uncompressed_size;
+}
+*/
+
+static void
+lzma_decoder_reset(lzma_coder *coder, const void *opt)
+{
+	uint32_t i, j, pos_state;
+	uint32_t num_pos_states;
+
+	const lzma_options_lzma *options = opt;
+
+	// NOTE: We assume that lc/lp/pb are valid since they were
+	// successfully decoded with lzma_lzma_decode_properties().
+
+	// Calculate pos_mask. We don't need pos_bits as is for anything.
+	coder->pos_mask = (1U << options->pb) - 1;
+
+	// Initialize the literal decoder.
+	literal_init(coder->literal, options->lc, options->lp);
+
+	coder->literal_context_bits = options->lc;
+	coder->literal_pos_mask = (1U << options->lp) - 1;
+
+	// State
+	coder->state = STATE_LIT_LIT;
+	coder->rep0 = 0;
+	coder->rep1 = 0;
+	coder->rep2 = 0;
+	coder->rep3 = 0;
+	coder->pos_mask = (1U << options->pb) - 1;
+
+	// Range decoder
+	rc_reset(coder->rc);
+
+	// Bit and bittree decoders
+	for (i = 0; i < STATES; ++i) {
+		for (j = 0; j <= coder->pos_mask; ++j) {
+			bit_reset(coder->is_match[i][j]);
+			bit_reset(coder->is_rep0_long[i][j]);
+		}
+
+		bit_reset(coder->is_rep[i]);
+		bit_reset(coder->is_rep0[i]);
+		bit_reset(coder->is_rep1[i]);
+		bit_reset(coder->is_rep2[i]);
+	}
+
+	for (i = 0; i < LEN_TO_POS_STATES; ++i)
+		bittree_reset(coder->pos_slot[i], POS_SLOT_BITS);
+
+	for (i = 0; i < FULL_DISTANCES - END_POS_MODEL_INDEX; ++i)
+		bit_reset(coder->pos_special[i]);
+
+	bittree_reset(coder->pos_align, ALIGN_BITS);
+
+	// Len decoders (also bit/bittree)
+	num_pos_states = 1U << options->pb;
+	bit_reset(coder->match_len_decoder.choice);
+	bit_reset(coder->match_len_decoder.choice2);
+	bit_reset(coder->rep_len_decoder.choice);
+	bit_reset(coder->rep_len_decoder.choice2);
+
+	for (pos_state = 0; pos_state < num_pos_states; ++pos_state) {
+		bittree_reset(coder->match_len_decoder.low[pos_state],
+				LEN_LOW_BITS);
+		bittree_reset(coder->match_len_decoder.mid[pos_state],
+				LEN_MID_BITS);
+
+		bittree_reset(coder->rep_len_decoder.low[pos_state],
+				LEN_LOW_BITS);
+		bittree_reset(coder->rep_len_decoder.mid[pos_state],
+				LEN_MID_BITS);
+	}
+
+	bittree_reset(coder->match_len_decoder.high, LEN_HIGH_BITS);
+	bittree_reset(coder->rep_len_decoder.high, LEN_HIGH_BITS);
+
+	coder->sequence = SEQ_IS_MATCH;
+	coder->probs = NULL;
+	coder->symbol = 0;
+	coder->limit = 0;
+	coder->offset = 0;
+	coder->len = 0;
+
+	return;
+}
+
+
+extern lzma_ret
+lzma_lzma_decoder_create(lzma_lz_decoder *lz, lzma_allocator *allocator,
+		const void *opt, lzma_lz_options *lz_options)
+{
+	const lzma_options_lzma *options = opt;
+
+	if (lz->coder == NULL) {
+		lz->coder = lzma_alloc(sizeof(lzma_coder), allocator);
+		if (lz->coder == NULL)
+			return LZMA_MEM_ERROR;
+
+		lz->code = &lzma_decode;
+		lz->reset = &lzma_decoder_reset;
+		lz->set_uncompressed = &lzma_decoder_uncompressed;
+	}
+
+	// All dictionary sizes are OK here. LZ decoder will take care of
+	// the special cases.
+	lz_options->dict_size = options->dict_size;
+	lz_options->preset_dict = options->preset_dict;
+	lz_options->preset_dict_size = options->preset_dict_size;
+
+	return LZMA_OK;
+}
+
+
+/// Allocate and initialize LZMA decoder. This is used only via LZ
+/// initialization (lzma_lzma_decoder_init() passes function pointer to
+/// the LZ initialization).
+static lzma_ret
+lzma_decoder_init(lzma_lz_decoder *lz, lzma_allocator *allocator,
+		const void *options, lzma_lz_options *lz_options)
+{
+	if (!is_lclppb_valid(options))
+		return LZMA_PROG_ERROR;
+
+	return_if_error(lzma_lzma_decoder_create(
+			lz, allocator, options, lz_options));
+
+	lzma_decoder_reset(lz->coder, options);
+	lzma_decoder_uncompressed(lz->coder, LZMA_VLI_UNKNOWN);
+
+	return LZMA_OK;
+}
+
+
+extern lzma_ret
+lzma_lzma_decoder_init(lzma_next_coder *next, lzma_allocator *allocator,
+		const lzma_filter_info *filters)
+{
+	// LZMA can only be the last filter in the chain. This is enforced
+	// by the raw_decoder initialization.
+	assert(filters[1].init == NULL);
+
+	return lzma_lz_decoder_init(next, allocator, filters,
+			&lzma_decoder_init);
+}
+
+
+extern bool
+lzma_lzma_lclppb_decode(lzma_options_lzma *options, uint8_t byte)
+{
+	if (byte > (4 * 5 + 4) * 9 + 8)
+		return true;
+
+	// See the file format specification to understand this.
+	options->pb = byte / (9 * 5);
+	byte -= options->pb * 9 * 5;
+	options->lp = byte / 9;
+	options->lc = byte - options->lp * 9;
+
+	return options->lc + options->lp > LZMA_LCLP_MAX;
+}
+
+
+extern uint64_t
+lzma_lzma_decoder_memusage_nocheck(const void *options)
+{
+	const lzma_options_lzma *const opt = options;
+	return sizeof(lzma_coder) + lzma_lz_decoder_memusage(opt->dict_size);
+}
+
+
+extern uint64_t
+lzma_lzma_decoder_memusage(const void *options)
+{
+	if (!is_lclppb_valid(options))
+		return UINT64_MAX;
+
+	return lzma_lzma_decoder_memusage_nocheck(options);
+}
+
+
+extern lzma_ret
+lzma_lzma_props_decode(void **options, lzma_allocator *allocator,
+		const uint8_t *props, size_t props_size)
+{
+	lzma_options_lzma *opt;
+
+	if (props_size != 5)
+		return LZMA_OPTIONS_ERROR;
+
+	opt = lzma_alloc(sizeof(lzma_options_lzma), allocator);
+	if (opt == NULL)
+		return LZMA_MEM_ERROR;
+
+	if (lzma_lzma_lclppb_decode(opt, props[0]))
+		goto error;
+
+	// All dictionary sizes are accepted, including zero. LZ decoder
+	// will automatically use a dictionary at least a few KiB even if
+	// a smaller dictionary is requested.
+	opt->dict_size = unaligned_read32le(props + 1);
+
+	opt->preset_dict = NULL;
+	opt->preset_dict_size = 0;
+
+	*options = opt;
+
+	return LZMA_OK;
+
+error:
+	lzma_free(opt, allocator);
+	return LZMA_OPTIONS_ERROR;
+}
diff --git a/Utilities/cmliblzma/liblzma/lzma/lzma_decoder.h b/Utilities/cmliblzma/liblzma/lzma/lzma_decoder.h
new file mode 100644
index 0000000..a463a76
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/lzma/lzma_decoder.h
@@ -0,0 +1,52 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       lzma_decoder.h
+/// \brief      LZMA decoder API
+///
+//  Authors:    Igor Pavlov
+//              Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#ifndef LZMA_LZMA_DECODER_H
+#define LZMA_LZMA_DECODER_H
+
+#include "common.h"
+
+
+/// Allocates and initializes LZMA decoder
+extern lzma_ret lzma_lzma_decoder_init(lzma_next_coder *next,
+		lzma_allocator *allocator, const lzma_filter_info *filters);
+
+extern uint64_t lzma_lzma_decoder_memusage(const void *options);
+
+extern lzma_ret lzma_lzma_props_decode(
+		void **options, lzma_allocator *allocator,
+		const uint8_t *props, size_t props_size);
+
+
+/// \brief      Decodes the LZMA Properties byte (lc/lp/pb)
+///
+/// \return     true if error occurred, false on success
+///
+extern bool lzma_lzma_lclppb_decode(
+		lzma_options_lzma *options, uint8_t byte);
+
+
+#ifdef LZMA_LZ_DECODER_H
+/// Allocate and setup function pointers only. This is used by LZMA1 and
+/// LZMA2 decoders.
+extern lzma_ret lzma_lzma_decoder_create(
+		lzma_lz_decoder *lz, lzma_allocator *allocator,
+		const void *opt, lzma_lz_options *lz_options);
+
+/// Gets memory usage without validating lc/lp/pb. This is used by LZMA2
+/// decoder, because raw LZMA2 decoding doesn't need lc/lp/pb.
+extern uint64_t lzma_lzma_decoder_memusage_nocheck(const void *options);
+
+#endif
+
+#endif
diff --git a/Utilities/cmliblzma/liblzma/lzma/lzma_encoder.c b/Utilities/cmliblzma/liblzma/lzma/lzma_encoder.c
new file mode 100644
index 0000000..e8738f4
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/lzma/lzma_encoder.c
@@ -0,0 +1,695 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       lzma_encoder.c
+/// \brief      LZMA encoder
+///
+//  Authors:    Igor Pavlov
+//              Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "lzma2_encoder.h"
+#include "lzma_encoder_private.h"
+#include "fastpos.h"
+
+
+/////////////
+// Literal //
+/////////////
+
+static inline void
+literal_matched(lzma_range_encoder *rc, probability *subcoder,
+		uint32_t match_byte, uint32_t symbol)
+{
+	uint32_t offset = 0x100;
+	symbol += UINT32_C(1) << 8;
+
+	do {
+		uint32_t match_bit;
+		uint32_t subcoder_index;
+		uint32_t bit;
+
+		match_byte <<= 1;
+		match_bit = match_byte & offset;
+		subcoder_index = offset + match_bit + (symbol >> 8);
+		bit = (symbol >> 7) & 1;
+		rc_bit(rc, &subcoder[subcoder_index], bit);
+
+		symbol <<= 1;
+		offset &= ~(match_byte ^ symbol);
+
+	} while (symbol < (UINT32_C(1) << 16));
+}
+
+
+static inline void
+literal(lzma_coder *coder, lzma_mf *mf, uint32_t position)
+{
+	// Locate the literal byte to be encoded and the subcoder.
+	const uint8_t cur_byte = mf->buffer[
+			mf->read_pos - mf->read_ahead];
+	probability *subcoder = literal_subcoder(coder->literal,
+			coder->literal_context_bits, coder->literal_pos_mask,
+			position, mf->buffer[mf->read_pos - mf->read_ahead - 1]);
+
+	if (is_literal_state(coder->state)) {
+		// Previous LZMA-symbol was a literal. Encode a normal
+		// literal without a match byte.
+		rc_bittree(&coder->rc, subcoder, 8, cur_byte);
+	} else {
+		// Previous LZMA-symbol was a match. Use the last byte of
+		// the match as a "match byte". That is, compare the bits
+		// of the current literal and the match byte.
+		const uint8_t match_byte = mf->buffer[
+				mf->read_pos - coder->reps[0] - 1
+				- mf->read_ahead];
+		literal_matched(&coder->rc, subcoder, match_byte, cur_byte);
+	}
+
+	update_literal(coder->state);
+}
+
+
+//////////////////
+// Match length //
+//////////////////
+
+static void
+length_update_prices(lzma_length_encoder *lc, const uint32_t pos_state)
+{
+	uint32_t a0, a1, b0, b1;
+	uint32_t *prices;
+	uint32_t i;
+
+	const uint32_t table_size = lc->table_size;
+	lc->counters[pos_state] = table_size;
+
+	a0 = rc_bit_0_price(lc->choice);
+	a1 = rc_bit_1_price(lc->choice);
+	b0 = a1 + rc_bit_0_price(lc->choice2);
+	b1 = a1 + rc_bit_1_price(lc->choice2);
+	prices = lc->prices[pos_state];
+
+	for (i = 0; i < table_size && i < LEN_LOW_SYMBOLS; ++i)
+		prices[i] = a0 + rc_bittree_price(lc->low[pos_state],
+				LEN_LOW_BITS, i);
+
+	for (; i < table_size && i < LEN_LOW_SYMBOLS + LEN_MID_SYMBOLS; ++i)
+		prices[i] = b0 + rc_bittree_price(lc->mid[pos_state],
+				LEN_MID_BITS, i - LEN_LOW_SYMBOLS);
+
+	for (; i < table_size; ++i)
+		prices[i] = b1 + rc_bittree_price(lc->high, LEN_HIGH_BITS,
+				i - LEN_LOW_SYMBOLS - LEN_MID_SYMBOLS);
+
+	return;
+}
+
+
+static inline void
+length(lzma_range_encoder *rc, lzma_length_encoder *lc,
+		const uint32_t pos_state, uint32_t len, const bool fast_mode)
+{
+	assert(len <= MATCH_LEN_MAX);
+	len -= MATCH_LEN_MIN;
+
+	if (len < LEN_LOW_SYMBOLS) {
+		rc_bit(rc, &lc->choice, 0);
+		rc_bittree(rc, lc->low[pos_state], LEN_LOW_BITS, len);
+	} else {
+		rc_bit(rc, &lc->choice, 1);
+		len -= LEN_LOW_SYMBOLS;
+
+		if (len < LEN_MID_SYMBOLS) {
+			rc_bit(rc, &lc->choice2, 0);
+			rc_bittree(rc, lc->mid[pos_state], LEN_MID_BITS, len);
+		} else {
+			rc_bit(rc, &lc->choice2, 1);
+			len -= LEN_MID_SYMBOLS;
+			rc_bittree(rc, lc->high, LEN_HIGH_BITS, len);
+		}
+	}
+
+	// Only getoptimum uses the prices so don't update the table when
+	// in fast mode.
+	if (!fast_mode)
+		if (--lc->counters[pos_state] == 0)
+			length_update_prices(lc, pos_state);
+}
+
+
+///////////
+// Match //
+///////////
+
+static inline void
+match(lzma_coder *coder, const uint32_t pos_state,
+		const uint32_t distance, const uint32_t len)
+{
+	uint32_t pos_slot;
+	uint32_t len_to_pos_state;
+
+	update_match(coder->state);
+
+	length(&coder->rc, &coder->match_len_encoder, pos_state, len,
+			coder->fast_mode);
+
+	pos_slot = get_pos_slot(distance);
+	len_to_pos_state = get_len_to_pos_state(len);
+	rc_bittree(&coder->rc, coder->pos_slot[len_to_pos_state],
+			POS_SLOT_BITS, pos_slot);
+
+	if (pos_slot >= START_POS_MODEL_INDEX) {
+		const uint32_t footer_bits = (pos_slot >> 1) - 1;
+		const uint32_t base = (2 | (pos_slot & 1)) << footer_bits;
+		const uint32_t pos_reduced = distance - base;
+
+		if (pos_slot < END_POS_MODEL_INDEX) {
+			// Careful here: base - pos_slot - 1 can be -1, but
+			// rc_bittree_reverse starts at probs[1], not probs[0].
+			rc_bittree_reverse(&coder->rc,
+				coder->pos_special + base - pos_slot - 1,
+				footer_bits, pos_reduced);
+		} else {
+			rc_direct(&coder->rc, pos_reduced >> ALIGN_BITS,
+					footer_bits - ALIGN_BITS);
+			rc_bittree_reverse(
+					&coder->rc, coder->pos_align,
+					ALIGN_BITS, pos_reduced & ALIGN_MASK);
+			++coder->align_price_count;
+		}
+	}
+
+	coder->reps[3] = coder->reps[2];
+	coder->reps[2] = coder->reps[1];
+	coder->reps[1] = coder->reps[0];
+	coder->reps[0] = distance;
+	++coder->match_price_count;
+}
+
+
+////////////////////
+// Repeated match //
+////////////////////
+
+static inline void
+rep_match(lzma_coder *coder, const uint32_t pos_state,
+		const uint32_t rep, const uint32_t len)
+{
+	if (rep == 0) {
+		rc_bit(&coder->rc, &coder->is_rep0[coder->state], 0);
+		rc_bit(&coder->rc,
+				&coder->is_rep0_long[coder->state][pos_state],
+				len != 1);
+	} else {
+		const uint32_t distance = coder->reps[rep];
+		rc_bit(&coder->rc, &coder->is_rep0[coder->state], 1);
+
+		if (rep == 1) {
+			rc_bit(&coder->rc, &coder->is_rep1[coder->state], 0);
+		} else {
+			rc_bit(&coder->rc, &coder->is_rep1[coder->state], 1);
+			rc_bit(&coder->rc, &coder->is_rep2[coder->state],
+					rep - 2);
+
+			if (rep == 3)
+				coder->reps[3] = coder->reps[2];
+
+			coder->reps[2] = coder->reps[1];
+		}
+
+		coder->reps[1] = coder->reps[0];
+		coder->reps[0] = distance;
+	}
+
+	if (len == 1) {
+		update_short_rep(coder->state);
+	} else {
+		length(&coder->rc, &coder->rep_len_encoder, pos_state, len,
+				coder->fast_mode);
+		update_long_rep(coder->state);
+	}
+}
+
+
+//////////
+// Main //
+//////////
+
+static void
+encode_symbol(lzma_coder *coder, lzma_mf *mf,
+		uint32_t back, uint32_t len, uint32_t position)
+{
+	const uint32_t pos_state = position & coder->pos_mask;
+
+	if (back == UINT32_MAX) {
+		// Literal i.e. eight-bit byte
+		assert(len == 1);
+		rc_bit(&coder->rc,
+				&coder->is_match[coder->state][pos_state], 0);
+		literal(coder, mf, position);
+	} else {
+		// Some type of match
+		rc_bit(&coder->rc,
+			&coder->is_match[coder->state][pos_state], 1);
+
+		if (back < REP_DISTANCES) {
+			// It's a repeated match i.e. the same distance
+			// has been used earlier.
+			rc_bit(&coder->rc, &coder->is_rep[coder->state], 1);
+			rep_match(coder, pos_state, back, len);
+		} else {
+			// Normal match
+			rc_bit(&coder->rc, &coder->is_rep[coder->state], 0);
+			match(coder, pos_state, back - REP_DISTANCES, len);
+		}
+	}
+
+	assert(mf->read_ahead >= len);
+	mf->read_ahead -= len;
+}
+
+
+static bool
+encode_init(lzma_coder *coder, lzma_mf *mf)
+{
+	assert(mf_position(mf) == 0);
+
+	if (mf->read_pos == mf->read_limit) {
+		if (mf->action == LZMA_RUN)
+			return false; // We cannot do anything.
+
+		// We are finishing (we cannot get here when flushing).
+		assert(mf->write_pos == mf->read_pos);
+		assert(mf->action == LZMA_FINISH);
+	} else {
+		// Do the actual initialization. The first LZMA symbol must
+		// always be a literal.
+		mf_skip(mf, 1);
+		mf->read_ahead = 0;
+		rc_bit(&coder->rc, &coder->is_match[0][0], 0);
+		rc_bittree(&coder->rc, coder->literal[0], 8, mf->buffer[0]);
+	}
+
+	// Initialization is done (except if empty file).
+	coder->is_initialized = true;
+
+	return true;
+}
+
+
+static void
+encode_eopm(lzma_coder *coder, uint32_t position)
+{
+	const uint32_t pos_state = position & coder->pos_mask;
+	rc_bit(&coder->rc, &coder->is_match[coder->state][pos_state], 1);
+	rc_bit(&coder->rc, &coder->is_rep[coder->state], 0);
+	match(coder, pos_state, UINT32_MAX, MATCH_LEN_MIN);
+}
+
+
+/// Number of bytes that a single encoding loop in lzma_lzma_encode() can
+/// consume from the dictionary. This limit comes from lzma_lzma_optimum()
+/// and may need to be updated if that function is significantly modified.
+#define LOOP_INPUT_MAX (OPTS + 1)
+
+
+extern lzma_ret
+lzma_lzma_encode(lzma_coder *LZMA_RESTRICT coder, lzma_mf *LZMA_RESTRICT mf,
+		uint8_t *LZMA_RESTRICT out, size_t *LZMA_RESTRICT out_pos,
+		size_t out_size, uint32_t limit)
+{
+	uint32_t position;
+
+	// Initialize the stream if no data has been encoded yet.
+	if (!coder->is_initialized && !encode_init(coder, mf))
+		return LZMA_OK;
+
+	// Get the lowest bits of the uncompressed offset from the LZ layer.
+	position = mf_position(mf);
+
+	while (true) {
+		uint32_t len;
+		uint32_t back;
+
+		// Encode pending bits, if any. Calling this before encoding
+		// the next symbol is needed only with plain LZMA, since
+		// LZMA2 always provides big enough buffer to flush
+		// everything out from the range encoder. For the same reason,
+		// rc_encode() never returns true when this function is used
+		// as part of LZMA2 encoder.
+		if (rc_encode(&coder->rc, out, out_pos, out_size)) {
+			assert(limit == UINT32_MAX);
+			return LZMA_OK;
+		}
+
+		// With LZMA2 we need to take care that compressed size of
+		// a chunk doesn't get too big.
+		// FIXME? Check if this could be improved.
+		if (limit != UINT32_MAX
+				&& (mf->read_pos - mf->read_ahead >= limit
+					|| *out_pos + rc_pending(&coder->rc)
+						>= LZMA2_CHUNK_MAX
+							- LOOP_INPUT_MAX))
+			break;
+
+		// Check that there is some input to process.
+		if (mf->read_pos >= mf->read_limit) {
+			if (mf->action == LZMA_RUN)
+				return LZMA_OK;
+
+			if (mf->read_ahead == 0)
+				break;
+		}
+
+		// Get optimal match (repeat position and length).
+		// Value ranges for pos:
+		//   - [0, REP_DISTANCES): repeated match
+		//   - [REP_DISTANCES, UINT32_MAX):
+		//     match at (pos - REP_DISTANCES)
+		//   - UINT32_MAX: not a match but a literal
+		// Value ranges for len:
+		//   - [MATCH_LEN_MIN, MATCH_LEN_MAX]
+
+		if (coder->fast_mode)
+			lzma_lzma_optimum_fast(coder, mf, &back, &len);
+		else
+			lzma_lzma_optimum_normal(
+					coder, mf, &back, &len, position);
+
+		encode_symbol(coder, mf, back, len, position);
+
+		position += len;
+	}
+
+	if (!coder->is_flushed) {
+		coder->is_flushed = true;
+
+		// We don't support encoding plain LZMA streams without EOPM,
+		// and LZMA2 doesn't use EOPM at LZMA level.
+		if (limit == UINT32_MAX)
+			encode_eopm(coder, position);
+
+		// Flush the remaining bytes from the range encoder.
+		rc_flush(&coder->rc);
+
+		// Copy the remaining bytes to the output buffer. If there
+		// isn't enough output space, we will copy out the remaining
+		// bytes on the next call to this function by using
+		// the rc_encode() call in the encoding loop above.
+		if (rc_encode(&coder->rc, out, out_pos, out_size)) {
+			assert(limit == UINT32_MAX);
+			return LZMA_OK;
+		}
+	}
+
+	// Make it ready for the next LZMA2 chunk.
+	coder->is_flushed = false;
+
+	return LZMA_STREAM_END;
+}
+
+
+static lzma_ret
+lzma_encode(lzma_coder *LZMA_RESTRICT coder, lzma_mf *LZMA_RESTRICT mf,
+		uint8_t *LZMA_RESTRICT out, size_t *LZMA_RESTRICT out_pos,
+		size_t out_size)
+{
+	// Plain LZMA has no support for sync-flushing.
+	if (unlikely(mf->action == LZMA_SYNC_FLUSH))
+		return LZMA_OPTIONS_ERROR;
+
+	return lzma_lzma_encode(coder, mf, out, out_pos, out_size, UINT32_MAX);
+}
+
+
+////////////////////
+// Initialization //
+////////////////////
+
+static bool
+is_options_valid(const lzma_options_lzma *options)
+{
+	// Validate some of the options. LZ encoder validates nice_len too
+	// but we need a valid value here earlier.
+	return is_lclppb_valid(options)
+			&& options->nice_len >= MATCH_LEN_MIN
+			&& options->nice_len <= MATCH_LEN_MAX
+			&& (options->mode == LZMA_MODE_FAST
+				|| options->mode == LZMA_MODE_NORMAL);
+}
+
+
+static void
+set_lz_options(lzma_lz_options *lz_options, const lzma_options_lzma *options)
+{
+	// LZ encoder initialization does the validation for these so we
+	// don't need to validate here.
+	lz_options->before_size = OPTS;
+	lz_options->dict_size = options->dict_size;
+	lz_options->after_size = LOOP_INPUT_MAX;
+	lz_options->match_len_max = MATCH_LEN_MAX;
+	lz_options->nice_len = options->nice_len;
+	lz_options->match_finder = options->mf;
+	lz_options->depth = options->depth;
+	lz_options->preset_dict = options->preset_dict;
+	lz_options->preset_dict_size = options->preset_dict_size;
+	return;
+}
+
+
+static void
+length_encoder_reset(lzma_length_encoder *lencoder,
+		const uint32_t num_pos_states, const bool fast_mode)
+{
+	size_t pos_state;
+
+	bit_reset(lencoder->choice);
+	bit_reset(lencoder->choice2);
+
+	for (pos_state = 0; pos_state < num_pos_states; ++pos_state) {
+		bittree_reset(lencoder->low[pos_state], LEN_LOW_BITS);
+		bittree_reset(lencoder->mid[pos_state], LEN_MID_BITS);
+	}
+
+	bittree_reset(lencoder->high, LEN_HIGH_BITS);
+
+	if (!fast_mode)
+		for (pos_state = 0; pos_state < num_pos_states;
+				++pos_state)
+			length_update_prices(lencoder, pos_state);
+
+	return;
+}
+
+
+extern lzma_ret
+lzma_lzma_encoder_reset(lzma_coder *coder, const lzma_options_lzma *options)
+{
+	size_t i, j;
+
+	if (!is_options_valid(options))
+		return LZMA_OPTIONS_ERROR;
+
+	coder->pos_mask = (1U << options->pb) - 1;
+	coder->literal_context_bits = options->lc;
+	coder->literal_pos_mask = (1U << options->lp) - 1;
+
+	// Range coder
+	rc_reset(&coder->rc);
+
+	// State
+	coder->state = STATE_LIT_LIT;
+	for (i = 0; i < REP_DISTANCES; ++i)
+		coder->reps[i] = 0;
+
+	literal_init(coder->literal, options->lc, options->lp);
+
+	// Bit encoders
+	for (i = 0; i < STATES; ++i) {
+		for (j = 0; j <= coder->pos_mask; ++j) {
+			bit_reset(coder->is_match[i][j]);
+			bit_reset(coder->is_rep0_long[i][j]);
+		}
+
+		bit_reset(coder->is_rep[i]);
+		bit_reset(coder->is_rep0[i]);
+		bit_reset(coder->is_rep1[i]);
+		bit_reset(coder->is_rep2[i]);
+	}
+
+	for (i = 0; i < FULL_DISTANCES - END_POS_MODEL_INDEX; ++i)
+		bit_reset(coder->pos_special[i]);
+
+	// Bit tree encoders
+	for (i = 0; i < LEN_TO_POS_STATES; ++i)
+		bittree_reset(coder->pos_slot[i], POS_SLOT_BITS);
+
+	bittree_reset(coder->pos_align, ALIGN_BITS);
+
+	// Length encoders
+	length_encoder_reset(&coder->match_len_encoder,
+			1U << options->pb, coder->fast_mode);
+
+	length_encoder_reset(&coder->rep_len_encoder,
+			1U << options->pb, coder->fast_mode);
+
+	// Price counts are incremented every time appropriate probabilities
+	// are changed. price counts are set to zero when the price tables
+	// are updated, which is done when the appropriate price counts have
+	// big enough value, and lzma_mf.read_ahead == 0 which happens at
+	// least every OPTS (a few thousand) possible price count increments.
+	//
+	// By resetting price counts to UINT32_MAX / 2, we make sure that the
+	// price tables will be initialized before they will be used (since
+	// the value is definitely big enough), and that it is OK to increment
+	// price counts without risk of integer overflow (since UINT32_MAX / 2
+	// is small enough). The current code doesn't increment price counts
+	// before initializing price tables, but it maybe done in future if
+	// we add support for saving the state between LZMA2 chunks.
+	coder->match_price_count = UINT32_MAX / 2;
+	coder->align_price_count = UINT32_MAX / 2;
+
+	coder->opts_end_index = 0;
+	coder->opts_current_index = 0;
+
+	return LZMA_OK;
+}
+
+
+extern lzma_ret
+lzma_lzma_encoder_create(lzma_coder **coder_ptr, lzma_allocator *allocator,
+		const lzma_options_lzma *options, lzma_lz_options *lz_options)
+{
+	lzma_coder *coder;
+	uint32_t log_size = 0;
+
+	// Allocate lzma_coder if it wasn't already allocated.
+	if (*coder_ptr == NULL) {
+		*coder_ptr = lzma_alloc(sizeof(lzma_coder), allocator);
+		if (*coder_ptr == NULL)
+			return LZMA_MEM_ERROR;
+	}
+
+	coder = *coder_ptr;
+
+	// Set compression mode. We haven't validates the options yet,
+	// but it's OK here, since nothing bad happens with invalid
+	// options in the code below, and they will get rejected by
+	// lzma_lzma_encoder_reset() call at the end of this function.
+	switch (options->mode) {
+		case LZMA_MODE_FAST:
+			coder->fast_mode = true;
+			break;
+
+		case LZMA_MODE_NORMAL: {
+			coder->fast_mode = false;
+
+			// Set dist_table_size.
+			// Round the dictionary size up to next 2^n.
+			while ((UINT32_C(1) << log_size) < options->dict_size)
+				++log_size;
+
+			coder->dist_table_size = log_size * 2;
+
+			// Length encoders' price table size
+			coder->match_len_encoder.table_size
+				= options->nice_len + 1 - MATCH_LEN_MIN;
+			coder->rep_len_encoder.table_size
+				= options->nice_len + 1 - MATCH_LEN_MIN;
+			break;
+		}
+
+		default:
+			return LZMA_OPTIONS_ERROR;
+	}
+
+	// We don't need to write the first byte as literal if there is
+	// a non-empty preset dictionary. encode_init() wouldn't even work
+	// if there is a non-empty preset dictionary, because encode_init()
+	// assumes that position is zero and previous byte is also zero.
+	coder->is_initialized = options->preset_dict != NULL
+			&& options->preset_dict_size > 0;
+	coder->is_flushed = false;
+
+	set_lz_options(lz_options, options);
+
+	return lzma_lzma_encoder_reset(coder, options);
+}
+
+
+static lzma_ret
+lzma_encoder_init(lzma_lz_encoder *lz, lzma_allocator *allocator,
+		const void *options, lzma_lz_options *lz_options)
+{
+	lz->code = &lzma_encode;
+	return lzma_lzma_encoder_create(
+			&lz->coder, allocator, options, lz_options);
+}
+
+
+extern lzma_ret
+lzma_lzma_encoder_init(lzma_next_coder *next, lzma_allocator *allocator,
+		const lzma_filter_info *filters)
+{
+	return lzma_lz_encoder_init(
+			next, allocator, filters, &lzma_encoder_init);
+}
+
+
+extern uint64_t
+lzma_lzma_encoder_memusage(const void *options)
+{
+	lzma_lz_options lz_options;
+	uint64_t lz_memusage;
+
+	if (!is_options_valid(options))
+		return UINT64_MAX;
+
+	set_lz_options(&lz_options, options);
+
+	lz_memusage = lzma_lz_encoder_memusage(&lz_options);
+	if (lz_memusage == UINT64_MAX)
+		return UINT64_MAX;
+
+	return (uint64_t)(sizeof(lzma_coder)) + lz_memusage;
+}
+
+
+extern bool
+lzma_lzma_lclppb_encode(const lzma_options_lzma *options, uint8_t *byte)
+{
+	if (!is_lclppb_valid(options))
+		return true;
+
+	*byte = (options->pb * 5 + options->lp) * 9 + options->lc;
+	assert(*byte <= (4 * 5 + 4) * 9 + 8);
+
+	return false;
+}
+
+
+#ifdef HAVE_ENCODER_LZMA1
+extern lzma_ret
+lzma_lzma_props_encode(const void *options, uint8_t *out)
+{
+	const lzma_options_lzma *const opt = options;
+
+	if (lzma_lzma_lclppb_encode(opt, out))
+		return LZMA_PROG_ERROR;
+
+	unaligned_write32le(out + 1, opt->dict_size);
+
+	return LZMA_OK;
+}
+#endif
+
+
+extern LZMA_API(lzma_bool)
+lzma_mode_is_supported(lzma_mode mode)
+{
+	return mode == LZMA_MODE_FAST || mode == LZMA_MODE_NORMAL;
+}
diff --git a/Utilities/cmliblzma/liblzma/lzma/lzma_encoder.h b/Utilities/cmliblzma/liblzma/lzma/lzma_encoder.h
new file mode 100644
index 0000000..abb8d8b
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/lzma/lzma_encoder.h
@@ -0,0 +1,54 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       lzma_encoder.h
+/// \brief      LZMA encoder API
+///
+//  Authors:    Igor Pavlov
+//              Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#ifndef LZMA_LZMA_ENCODER_H
+#define LZMA_LZMA_ENCODER_H
+
+#include "common.h"
+
+
+extern lzma_ret lzma_lzma_encoder_init(lzma_next_coder *next,
+		lzma_allocator *allocator, const lzma_filter_info *filters);
+
+
+extern uint64_t lzma_lzma_encoder_memusage(const void *options);
+
+extern lzma_ret lzma_lzma_props_encode(const void *options, uint8_t *out);
+
+
+/// Encodes lc/lp/pb into one byte. Returns false on success and true on error.
+extern bool lzma_lzma_lclppb_encode(
+		const lzma_options_lzma *options, uint8_t *byte);
+
+
+#ifdef LZMA_LZ_ENCODER_H
+
+/// Initializes raw LZMA encoder; this is used by LZMA2.
+extern lzma_ret lzma_lzma_encoder_create(
+		lzma_coder **coder_ptr, lzma_allocator *allocator,
+		const lzma_options_lzma *options, lzma_lz_options *lz_options);
+
+
+/// Resets an already initialized LZMA encoder; this is used by LZMA2.
+extern lzma_ret lzma_lzma_encoder_reset(
+		lzma_coder *coder, const lzma_options_lzma *options);
+
+
+extern lzma_ret lzma_lzma_encode(lzma_coder *LZMA_RESTRICT coder,
+		lzma_mf *LZMA_RESTRICT mf, uint8_t *LZMA_RESTRICT out,
+		size_t *LZMA_RESTRICT out_pos, size_t out_size,
+		uint32_t read_limit);
+
+#endif
+
+#endif
diff --git a/Utilities/cmliblzma/liblzma/lzma/lzma_encoder_optimum_fast.c b/Utilities/cmliblzma/liblzma/lzma/lzma_encoder_optimum_fast.c
new file mode 100644
index 0000000..f983126
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/lzma/lzma_encoder_optimum_fast.c
@@ -0,0 +1,185 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       lzma_encoder_optimum_fast.c
+//
+//  Author:     Igor Pavlov
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "lzma_encoder_private.h"
+
+
+#define change_pair(small_dist, big_dist) \
+	(((big_dist) >> 7) > (small_dist))
+
+
+extern void
+lzma_lzma_optimum_fast(lzma_coder *LZMA_RESTRICT coder, lzma_mf *LZMA_RESTRICT mf,
+		uint32_t *LZMA_RESTRICT back_res, uint32_t *LZMA_RESTRICT len_res)
+{
+	const uint8_t *buf;
+	uint32_t buf_avail;
+	uint32_t i;
+	uint32_t rep_len = 0;
+	uint32_t rep_index = 0;
+	uint32_t back_main = 0;
+	uint32_t limit;
+
+	const uint32_t nice_len = mf->nice_len;
+
+	uint32_t len_main;
+	uint32_t matches_count;
+	if (mf->read_ahead == 0) {
+		len_main = mf_find(mf, &matches_count, coder->matches);
+	} else {
+		assert(mf->read_ahead == 1);
+		len_main = coder->longest_match_length;
+		matches_count = coder->matches_count;
+	}
+
+	buf = mf_ptr(mf) - 1;
+	buf_avail = my_min(mf_avail(mf) + 1, MATCH_LEN_MAX);
+
+	if (buf_avail < 2) {
+		// There's not enough input left to encode a match.
+		*back_res = UINT32_MAX;
+		*len_res = 1;
+		return;
+	}
+
+	// Look for repeated matches; scan the previous four match distances
+	for (i = 0; i < REP_DISTANCES; ++i) {
+		uint32_t len;
+
+		// Pointer to the beginning of the match candidate
+		const uint8_t *const buf_back = buf - coder->reps[i] - 1;
+
+		// If the first two bytes (2 == MATCH_LEN_MIN) do not match,
+		// this rep is not useful.
+		if (not_equal_16(buf, buf_back))
+			continue;
+
+		// The first two bytes matched.
+		// Calculate the length of the match.
+		for (len = 2; len < buf_avail
+				&& buf[len] == buf_back[len]; ++len) ;
+
+		// If we have found a repeated match that is at least
+		// nice_len long, return it immediately.
+		if (len >= nice_len) {
+			*back_res = i;
+			*len_res = len;
+			mf_skip(mf, len - 1);
+			return;
+		}
+
+		if (len > rep_len) {
+			rep_index = i;
+			rep_len = len;
+		}
+	}
+
+	// We didn't find a long enough repeated match. Encode it as a normal
+	// match if the match length is at least nice_len.
+	if (len_main >= nice_len) {
+		*back_res = coder->matches[matches_count - 1].dist
+				+ REP_DISTANCES;
+		*len_res = len_main;
+		mf_skip(mf, len_main - 1);
+		return;
+	}
+
+	if (len_main >= 2) {
+		back_main = coder->matches[matches_count - 1].dist;
+
+		while (matches_count > 1 && len_main ==
+				coder->matches[matches_count - 2].len + 1) {
+			if (!change_pair(coder->matches[
+						matches_count - 2].dist,
+					back_main))
+				break;
+
+			--matches_count;
+			len_main = coder->matches[matches_count - 1].len;
+			back_main = coder->matches[matches_count - 1].dist;
+		}
+
+		if (len_main == 2 && back_main >= 0x80)
+			len_main = 1;
+	}
+
+	if (rep_len >= 2) {
+		if (rep_len + 1 >= len_main
+				|| (rep_len + 2 >= len_main
+					&& back_main > (UINT32_C(1) << 9))
+				|| (rep_len + 3 >= len_main
+					&& back_main > (UINT32_C(1) << 15))) {
+			*back_res = rep_index;
+			*len_res = rep_len;
+			mf_skip(mf, rep_len - 1);
+			return;
+		}
+	}
+
+	if (len_main < 2 || buf_avail <= 2) {
+		*back_res = UINT32_MAX;
+		*len_res = 1;
+		return;
+	}
+
+	// Get the matches for the next byte. If we find a better match,
+	// the current byte is encoded as a literal.
+	coder->longest_match_length = mf_find(mf,
+			&coder->matches_count, coder->matches);
+
+	if (coder->longest_match_length >= 2) {
+		const uint32_t new_dist = coder->matches[
+				coder->matches_count - 1].dist;
+
+		if ((coder->longest_match_length >= len_main
+					&& new_dist < back_main)
+				|| (coder->longest_match_length == len_main + 1
+					&& !change_pair(back_main, new_dist))
+				|| (coder->longest_match_length > len_main + 1)
+				|| (coder->longest_match_length + 1 >= len_main
+					&& len_main >= 3
+					&& change_pair(new_dist, back_main))) {
+			*back_res = UINT32_MAX;
+			*len_res = 1;
+			return;
+		}
+	}
+
+	// In contrast to LZMA SDK, dictionary could not have been moved
+	// between mf_find() calls, thus it is safe to just increment
+	// the old buf pointer instead of recalculating it with mf_ptr().
+	++buf;
+
+	limit = len_main - 1;
+
+	for (i = 0; i < REP_DISTANCES; ++i) {
+		uint32_t len;
+
+		const uint8_t *const buf_back = buf - coder->reps[i] - 1;
+
+		if (not_equal_16(buf, buf_back))
+			continue;
+
+		for (len = 2; len < limit
+				&& buf[len] == buf_back[len]; ++len) ;
+
+		if (len >= limit) {
+			*back_res = UINT32_MAX;
+			*len_res = 1;
+			return;
+		}
+	}
+
+	*back_res = back_main + REP_DISTANCES;
+	*len_res = len_main;
+	mf_skip(mf, len_main - 2);
+	return;
+}
diff --git a/Utilities/cmliblzma/liblzma/lzma/lzma_encoder_optimum_normal.c b/Utilities/cmliblzma/liblzma/lzma/lzma_encoder_optimum_normal.c
new file mode 100644
index 0000000..d3a6348
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/lzma/lzma_encoder_optimum_normal.c
@@ -0,0 +1,925 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       lzma_encoder_optimum_normal.c
+//
+//  Author:     Igor Pavlov
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "lzma_encoder_private.h"
+#include "fastpos.h"
+
+
+////////////
+// Prices //
+////////////
+
+static uint32_t
+get_literal_price(const lzma_coder *const coder, const uint32_t pos,
+		const uint32_t prev_byte, const bool match_mode,
+		uint32_t match_byte, uint32_t symbol)
+{
+	const probability *const subcoder = literal_subcoder(coder->literal,
+			coder->literal_context_bits, coder->literal_pos_mask,
+			pos, prev_byte);
+
+	uint32_t price = 0;
+
+	if (!match_mode) {
+		price = rc_bittree_price(subcoder, 8, symbol);
+	} else {
+		uint32_t offset = 0x100;
+		symbol += UINT32_C(1) << 8;
+
+		do {
+			uint32_t match_bit;
+			uint32_t subcoder_index;
+			uint32_t bit;
+
+			match_byte <<= 1;
+
+			match_bit = match_byte & offset;
+			subcoder_index = offset + match_bit + (symbol >> 8);
+			bit = (symbol >> 7) & 1;
+			price += rc_bit_price(subcoder[subcoder_index], bit);
+
+			symbol <<= 1;
+			offset &= ~(match_byte ^ symbol);
+
+		} while (symbol < (UINT32_C(1) << 16));
+	}
+
+	return price;
+}
+
+
+static inline uint32_t
+get_len_price(const lzma_length_encoder *const lencoder,
+		const uint32_t len, const uint32_t pos_state)
+{
+	// NOTE: Unlike the other price tables, length prices are updated
+	// in lzma_encoder.c
+	return lencoder->prices[pos_state][len - MATCH_LEN_MIN];
+}
+
+
+static inline uint32_t
+get_short_rep_price(const lzma_coder *const coder,
+		const lzma_lzma_state state, const uint32_t pos_state)
+{
+	return rc_bit_0_price(coder->is_rep0[state])
+		+ rc_bit_0_price(coder->is_rep0_long[state][pos_state]);
+}
+
+
+static inline uint32_t
+get_pure_rep_price(const lzma_coder *const coder, const uint32_t rep_index,
+		const lzma_lzma_state state, uint32_t pos_state)
+{
+	uint32_t price;
+
+	if (rep_index == 0) {
+		price = rc_bit_0_price(coder->is_rep0[state]);
+		price += rc_bit_1_price(coder->is_rep0_long[state][pos_state]);
+	} else {
+		price = rc_bit_1_price(coder->is_rep0[state]);
+
+		if (rep_index == 1) {
+			price += rc_bit_0_price(coder->is_rep1[state]);
+		} else {
+			price += rc_bit_1_price(coder->is_rep1[state]);
+			price += rc_bit_price(coder->is_rep2[state],
+					rep_index - 2);
+		}
+	}
+
+	return price;
+}
+
+
+static inline uint32_t
+get_rep_price(const lzma_coder *const coder, const uint32_t rep_index,
+		const uint32_t len, const lzma_lzma_state state,
+		const uint32_t pos_state)
+{
+	return get_len_price(&coder->rep_len_encoder, len, pos_state)
+		+ get_pure_rep_price(coder, rep_index, state, pos_state);
+}
+
+
+static inline uint32_t
+get_pos_len_price(const lzma_coder *const coder, const uint32_t pos,
+		const uint32_t len, const uint32_t pos_state)
+{
+	const uint32_t len_to_pos_state = get_len_to_pos_state(len);
+	uint32_t price;
+
+	if (pos < FULL_DISTANCES) {
+		price = coder->distances_prices[len_to_pos_state][pos];
+	} else {
+		const uint32_t pos_slot = get_pos_slot_2(pos);
+		price = coder->pos_slot_prices[len_to_pos_state][pos_slot]
+				+ coder->align_prices[pos & ALIGN_MASK];
+	}
+
+	price += get_len_price(&coder->match_len_encoder, len, pos_state);
+
+	return price;
+}
+
+
+static void
+fill_distances_prices(lzma_coder *coder)
+{
+	uint32_t len_to_pos_state;
+	uint32_t pos_slot;
+	uint32_t i;
+
+	for (len_to_pos_state = 0;
+			len_to_pos_state < LEN_TO_POS_STATES;
+			++len_to_pos_state) {
+
+		uint32_t *const pos_slot_prices
+				= coder->pos_slot_prices[len_to_pos_state];
+
+		// Price to encode the pos_slot.
+		for (pos_slot = 0;
+				pos_slot < coder->dist_table_size; ++pos_slot)
+			pos_slot_prices[pos_slot] = rc_bittree_price(
+					coder->pos_slot[len_to_pos_state],
+					POS_SLOT_BITS, pos_slot);
+
+		// For matches with distance >= FULL_DISTANCES, add the price
+		// of the direct bits part of the match distance. (Align bits
+		// are handled by fill_align_prices()).
+		for (pos_slot = END_POS_MODEL_INDEX;
+				pos_slot < coder->dist_table_size; ++pos_slot)
+			pos_slot_prices[pos_slot] += rc_direct_price(
+					((pos_slot >> 1) - 1) - ALIGN_BITS);
+
+		// Distances in the range [0, 3] are fully encoded with
+		// pos_slot, so they are used for coder->distances_prices
+		// as is.
+		for (i = 0; i < START_POS_MODEL_INDEX; ++i)
+			coder->distances_prices[len_to_pos_state][i]
+					= pos_slot_prices[i];
+	}
+
+	// Distances in the range [4, 127] depend on pos_slot and pos_special.
+	// We do this in a loop separate from the above loop to avoid
+	// redundant calls to get_pos_slot().
+	for (i = START_POS_MODEL_INDEX; i < FULL_DISTANCES; ++i) {
+		const uint32_t pos_slot = get_pos_slot(i);
+		const uint32_t footer_bits = ((pos_slot >> 1) - 1);
+		const uint32_t base = (2 | (pos_slot & 1)) << footer_bits;
+		const uint32_t price = rc_bittree_reverse_price(
+				coder->pos_special + base - pos_slot - 1,
+				footer_bits, i - base);
+
+		for (len_to_pos_state = 0;
+				len_to_pos_state < LEN_TO_POS_STATES;
+				++len_to_pos_state)
+			coder->distances_prices[len_to_pos_state][i]
+					= price + coder->pos_slot_prices[
+						len_to_pos_state][pos_slot];
+	}
+
+	coder->match_price_count = 0;
+	return;
+}
+
+
+static void
+fill_align_prices(lzma_coder *coder)
+{
+	uint32_t i;
+	for (i = 0; i < ALIGN_TABLE_SIZE; ++i)
+		coder->align_prices[i] = rc_bittree_reverse_price(
+				coder->pos_align, ALIGN_BITS, i);
+
+	coder->align_price_count = 0;
+	return;
+}
+
+
+/////////////
+// Optimal //
+/////////////
+
+static inline void
+make_literal(lzma_optimal *optimal)
+{
+	optimal->back_prev = UINT32_MAX;
+	optimal->prev_1_is_literal = false;
+}
+
+
+static inline void
+make_short_rep(lzma_optimal *optimal)
+{
+	optimal->back_prev = 0;
+	optimal->prev_1_is_literal = false;
+}
+
+
+#define is_short_rep(optimal) \
+	((optimal).back_prev == 0)
+
+
+static void
+backward(lzma_coder *LZMA_RESTRICT coder, uint32_t *LZMA_RESTRICT len_res,
+		uint32_t *LZMA_RESTRICT back_res, uint32_t cur)
+{
+	uint32_t pos_mem = coder->opts[cur].pos_prev;
+	uint32_t back_mem = coder->opts[cur].back_prev;
+
+	coder->opts_end_index = cur;
+
+	do {
+		const uint32_t pos_prev = pos_mem;
+		const uint32_t back_cur = back_mem;
+
+		if (coder->opts[cur].prev_1_is_literal) {
+			make_literal(&coder->opts[pos_mem]);
+			coder->opts[pos_mem].pos_prev = pos_mem - 1;
+
+			if (coder->opts[cur].prev_2) {
+				coder->opts[pos_mem - 1].prev_1_is_literal
+						= false;
+				coder->opts[pos_mem - 1].pos_prev
+						= coder->opts[cur].pos_prev_2;
+				coder->opts[pos_mem - 1].back_prev
+						= coder->opts[cur].back_prev_2;
+			}
+		}
+
+		back_mem = coder->opts[pos_prev].back_prev;
+		pos_mem = coder->opts[pos_prev].pos_prev;
+
+		coder->opts[pos_prev].back_prev = back_cur;
+		coder->opts[pos_prev].pos_prev = cur;
+		cur = pos_prev;
+
+	} while (cur != 0);
+
+	coder->opts_current_index = coder->opts[0].pos_prev;
+	*len_res = coder->opts[0].pos_prev;
+	*back_res = coder->opts[0].back_prev;
+
+	return;
+}
+
+
+//////////
+// Main //
+//////////
+
+static inline uint32_t
+helper1(lzma_coder *LZMA_RESTRICT coder, lzma_mf *LZMA_RESTRICT mf,
+		uint32_t *LZMA_RESTRICT back_res, uint32_t *LZMA_RESTRICT len_res,
+		uint32_t position)
+{
+	uint32_t buf_avail;
+	const uint8_t *buf;
+	uint32_t rep_lens[REP_DISTANCES];
+	uint32_t rep_max_index = 0;
+	uint32_t i;
+
+	uint8_t current_byte;
+	uint8_t match_byte;
+
+	uint32_t pos_state;
+	uint32_t match_price;
+	uint32_t rep_match_price;
+	uint32_t len_end;
+	uint32_t len;
+
+	uint32_t normal_match_price;
+
+	const uint32_t nice_len = mf->nice_len;
+
+	uint32_t len_main;
+	uint32_t matches_count;
+
+	if (mf->read_ahead == 0) {
+		len_main = mf_find(mf, &matches_count, coder->matches);
+	} else {
+		assert(mf->read_ahead == 1);
+		len_main = coder->longest_match_length;
+		matches_count = coder->matches_count;
+	}
+
+	buf_avail = my_min(mf_avail(mf) + 1, MATCH_LEN_MAX);
+	if (buf_avail < 2) {
+		*back_res = UINT32_MAX;
+		*len_res = 1;
+		return UINT32_MAX;
+	}
+
+	buf = mf_ptr(mf) - 1;
+
+	for (i = 0; i < REP_DISTANCES; ++i) {
+		uint32_t len_test;
+
+		const uint8_t *const buf_back = buf - coder->reps[i] - 1;
+
+		if (not_equal_16(buf, buf_back)) {
+			rep_lens[i] = 0;
+			continue;
+		}
+
+		for (len_test = 2; len_test < buf_avail
+				&& buf[len_test] == buf_back[len_test];
+				++len_test) ;
+
+		rep_lens[i] = len_test;
+		if (len_test > rep_lens[rep_max_index])
+			rep_max_index = i;
+	}
+
+	if (rep_lens[rep_max_index] >= nice_len) {
+		*back_res = rep_max_index;
+		*len_res = rep_lens[rep_max_index];
+		mf_skip(mf, *len_res - 1);
+		return UINT32_MAX;
+	}
+
+
+	if (len_main >= nice_len) {
+		*back_res = coder->matches[matches_count - 1].dist
+				+ REP_DISTANCES;
+		*len_res = len_main;
+		mf_skip(mf, len_main - 1);
+		return UINT32_MAX;
+	}
+
+	current_byte = *buf;
+	match_byte = *(buf - coder->reps[0] - 1);
+
+	if (len_main < 2 && current_byte != match_byte
+			&& rep_lens[rep_max_index] < 2) {
+		*back_res = UINT32_MAX;
+		*len_res = 1;
+		return UINT32_MAX;
+	}
+
+	coder->opts[0].state = coder->state;
+
+	pos_state = position & coder->pos_mask;
+
+	coder->opts[1].price = rc_bit_0_price(
+				coder->is_match[coder->state][pos_state])
+			+ get_literal_price(coder, position, buf[-1],
+				!is_literal_state(coder->state),
+				match_byte, current_byte);
+
+	make_literal(&coder->opts[1]);
+
+	match_price = rc_bit_1_price(
+			coder->is_match[coder->state][pos_state]);
+	rep_match_price = match_price
+			+ rc_bit_1_price(coder->is_rep[coder->state]);
+
+	if (match_byte == current_byte) {
+		const uint32_t short_rep_price = rep_match_price
+				+ get_short_rep_price(
+					coder, coder->state, pos_state);
+
+		if (short_rep_price < coder->opts[1].price) {
+			coder->opts[1].price = short_rep_price;
+			make_short_rep(&coder->opts[1]);
+		}
+	}
+
+	len_end = my_max(len_main, rep_lens[rep_max_index]);
+
+	if (len_end < 2) {
+		*back_res = coder->opts[1].back_prev;
+		*len_res = 1;
+		return UINT32_MAX;
+	}
+
+	coder->opts[1].pos_prev = 0;
+
+	for (i = 0; i < REP_DISTANCES; ++i)
+		coder->opts[0].backs[i] = coder->reps[i];
+
+	len = len_end;
+	do {
+		coder->opts[len].price = RC_INFINITY_PRICE;
+	} while (--len >= 2);
+
+
+	for (i = 0; i < REP_DISTANCES; ++i) {
+		uint32_t price;
+
+		uint32_t rep_len = rep_lens[i];
+		if (rep_len < 2)
+			continue;
+
+		price = rep_match_price + get_pure_rep_price(
+				coder, i, coder->state, pos_state);
+
+		do {
+			const uint32_t cur_and_len_price = price
+					+ get_len_price(
+						&coder->rep_len_encoder,
+						rep_len, pos_state);
+
+			if (cur_and_len_price < coder->opts[rep_len].price) {
+				coder->opts[rep_len].price = cur_and_len_price;
+				coder->opts[rep_len].pos_prev = 0;
+				coder->opts[rep_len].back_prev = i;
+				coder->opts[rep_len].prev_1_is_literal = false;
+			}
+		} while (--rep_len >= 2);
+	}
+
+
+	normal_match_price = match_price
+			+ rc_bit_0_price(coder->is_rep[coder->state]);
+
+	len = rep_lens[0] >= 2 ? rep_lens[0] + 1 : 2;
+	if (len <= len_main) {
+		uint32_t i = 0;
+		while (len > coder->matches[i].len)
+			++i;
+
+		for(; ; ++len) {
+			const uint32_t dist = coder->matches[i].dist;
+			const uint32_t cur_and_len_price = normal_match_price
+					+ get_pos_len_price(coder,
+						dist, len, pos_state);
+
+			if (cur_and_len_price < coder->opts[len].price) {
+				coder->opts[len].price = cur_and_len_price;
+				coder->opts[len].pos_prev = 0;
+				coder->opts[len].back_prev
+						= dist + REP_DISTANCES;
+				coder->opts[len].prev_1_is_literal = false;
+			}
+
+			if (len == coder->matches[i].len)
+				if (++i == matches_count)
+					break;
+		}
+	}
+
+	return len_end;
+}
+
+
+static inline uint32_t
+helper2(lzma_coder *coder, uint32_t *reps, const uint8_t *buf,
+		uint32_t len_end, uint32_t position, const uint32_t cur,
+		const uint32_t nice_len, const uint32_t buf_avail_full)
+{
+	uint32_t matches_count = coder->matches_count;
+	uint32_t new_len = coder->longest_match_length;
+	uint32_t pos_prev = coder->opts[cur].pos_prev;
+	lzma_lzma_state state;
+	uint32_t buf_avail;
+	uint32_t rep_index;
+	uint32_t i;
+
+	uint32_t cur_price;
+	uint8_t current_byte;
+	uint8_t match_byte;
+	uint32_t pos_state;
+	uint32_t cur_and_1_price;
+	bool next_is_literal = false;
+	uint32_t match_price;
+	uint32_t rep_match_price;
+	uint32_t start_len = 2;
+
+	if (coder->opts[cur].prev_1_is_literal) {
+		--pos_prev;
+
+		if (coder->opts[cur].prev_2) {
+			state = coder->opts[coder->opts[cur].pos_prev_2].state;
+
+			if (coder->opts[cur].back_prev_2 < REP_DISTANCES)
+				update_long_rep(state);
+			else
+				update_match(state);
+
+		} else {
+			state = coder->opts[pos_prev].state;
+		}
+
+		update_literal(state);
+
+	} else {
+		state = coder->opts[pos_prev].state;
+	}
+
+	if (pos_prev == cur - 1) {
+		if (is_short_rep(coder->opts[cur]))
+			update_short_rep(state);
+		else
+			update_literal(state);
+	} else {
+		uint32_t pos;
+		if (coder->opts[cur].prev_1_is_literal
+				&& coder->opts[cur].prev_2) {
+			pos_prev = coder->opts[cur].pos_prev_2;
+			pos = coder->opts[cur].back_prev_2;
+			update_long_rep(state);
+		} else {
+			pos = coder->opts[cur].back_prev;
+			if (pos < REP_DISTANCES)
+				update_long_rep(state);
+			else
+				update_match(state);
+		}
+
+		if (pos < REP_DISTANCES) {
+			uint32_t i;
+
+			reps[0] = coder->opts[pos_prev].backs[pos];
+
+			for (i = 1; i <= pos; ++i)
+				reps[i] = coder->opts[pos_prev].backs[i - 1];
+
+			for (; i < REP_DISTANCES; ++i)
+				reps[i] = coder->opts[pos_prev].backs[i];
+
+		} else {
+			reps[0] = pos - REP_DISTANCES;
+
+			for (i = 1; i < REP_DISTANCES; ++i)
+				reps[i] = coder->opts[pos_prev].backs[i - 1];
+		}
+	}
+
+	coder->opts[cur].state = state;
+
+	for (i = 0; i < REP_DISTANCES; ++i)
+		coder->opts[cur].backs[i] = reps[i];
+
+	cur_price = coder->opts[cur].price;
+
+	current_byte = *buf;
+	match_byte = *(buf - reps[0] - 1);
+
+	pos_state = position & coder->pos_mask;
+
+	cur_and_1_price = cur_price
+			+ rc_bit_0_price(coder->is_match[state][pos_state])
+			+ get_literal_price(coder, position, buf[-1],
+			!is_literal_state(state), match_byte, current_byte);
+
+	if (cur_and_1_price < coder->opts[cur + 1].price) {
+		coder->opts[cur + 1].price = cur_and_1_price;
+		coder->opts[cur + 1].pos_prev = cur;
+		make_literal(&coder->opts[cur + 1]);
+		next_is_literal = true;
+	}
+
+	match_price = cur_price
+			+ rc_bit_1_price(coder->is_match[state][pos_state]);
+	rep_match_price = match_price
+			+ rc_bit_1_price(coder->is_rep[state]);
+
+	if (match_byte == current_byte
+			&& !(coder->opts[cur + 1].pos_prev < cur
+				&& coder->opts[cur + 1].back_prev == 0)) {
+
+		const uint32_t short_rep_price = rep_match_price
+				+ get_short_rep_price(coder, state, pos_state);
+
+		if (short_rep_price <= coder->opts[cur + 1].price) {
+			coder->opts[cur + 1].price = short_rep_price;
+			coder->opts[cur + 1].pos_prev = cur;
+			make_short_rep(&coder->opts[cur + 1]);
+			next_is_literal = true;
+		}
+	}
+
+	if (buf_avail_full < 2)
+		return len_end;
+
+	buf_avail = my_min(buf_avail_full, nice_len);
+
+	if (!next_is_literal && match_byte != current_byte) { // speed optimization
+		// try literal + rep0
+		const uint8_t *const buf_back = buf - reps[0] - 1;
+		const uint32_t limit = my_min(buf_avail_full, nice_len + 1);
+
+		uint32_t len_test = 1;
+		while (len_test < limit && buf[len_test] == buf_back[len_test])
+			++len_test;
+
+		--len_test;
+
+		if (len_test >= 2) {
+			uint32_t pos_state_next;
+			uint32_t next_rep_match_price;
+			uint32_t offset;
+			uint32_t cur_and_len_price;
+
+			lzma_lzma_state state_2 = state;
+			update_literal(state_2);
+
+			pos_state_next = (position + 1) & coder->pos_mask;
+			next_rep_match_price = cur_and_1_price
+					+ rc_bit_1_price(coder->is_match[state_2][pos_state_next])
+					+ rc_bit_1_price(coder->is_rep[state_2]);
+
+			//for (; len_test >= 2; --len_test) {
+			offset = cur + 1 + len_test;
+
+			while (len_end < offset)
+				coder->opts[++len_end].price = RC_INFINITY_PRICE;
+
+			cur_and_len_price = next_rep_match_price
+					+ get_rep_price(coder, 0, len_test,
+						state_2, pos_state_next);
+
+			if (cur_and_len_price < coder->opts[offset].price) {
+				coder->opts[offset].price = cur_and_len_price;
+				coder->opts[offset].pos_prev = cur + 1;
+				coder->opts[offset].back_prev = 0;
+				coder->opts[offset].prev_1_is_literal = true;
+				coder->opts[offset].prev_2 = false;
+			}
+			//}
+		}
+	}
+
+
+	for (rep_index = 0; rep_index < REP_DISTANCES; ++rep_index) {
+		uint32_t len_test, len_test_2, len_test_temp;
+		uint32_t price, limit;
+
+		const uint8_t *const buf_back = buf - reps[rep_index] - 1;
+		if (not_equal_16(buf, buf_back))
+			continue;
+
+		for (len_test = 2; len_test < buf_avail
+				&& buf[len_test] == buf_back[len_test];
+				++len_test) ;
+
+		while (len_end < cur + len_test)
+			coder->opts[++len_end].price = RC_INFINITY_PRICE;
+
+		len_test_temp = len_test;
+		price = rep_match_price + get_pure_rep_price(
+				coder, rep_index, state, pos_state);
+
+		do {
+			const uint32_t cur_and_len_price = price
+					+ get_len_price(&coder->rep_len_encoder,
+							len_test, pos_state);
+
+			if (cur_and_len_price < coder->opts[cur + len_test].price) {
+				coder->opts[cur + len_test].price = cur_and_len_price;
+				coder->opts[cur + len_test].pos_prev = cur;
+				coder->opts[cur + len_test].back_prev = rep_index;
+				coder->opts[cur + len_test].prev_1_is_literal = false;
+			}
+		} while (--len_test >= 2);
+
+		len_test = len_test_temp;
+
+		if (rep_index == 0)
+			start_len = len_test + 1;
+
+
+		len_test_2 = len_test + 1;
+		limit = my_min(buf_avail_full,
+				len_test_2 + nice_len);
+		for (; len_test_2 < limit
+				&& buf[len_test_2] == buf_back[len_test_2];
+				++len_test_2) ;
+
+		len_test_2 -= len_test + 1;
+
+		if (len_test_2 >= 2) {
+			uint32_t pos_state_next;
+			uint32_t cur_and_len_literal_price;
+			uint32_t next_rep_match_price;
+			uint32_t offset;
+			uint32_t cur_and_len_price;
+
+			lzma_lzma_state state_2 = state;
+			update_long_rep(state_2);
+
+			pos_state_next = (position + len_test) & coder->pos_mask;
+
+			cur_and_len_literal_price = price
+					+ get_len_price(&coder->rep_len_encoder,
+						len_test, pos_state)
+					+ rc_bit_0_price(coder->is_match[state_2][pos_state_next])
+					+ get_literal_price(coder, position + len_test,
+						buf[len_test - 1], true,
+						buf_back[len_test], buf[len_test]);
+
+			update_literal(state_2);
+
+			pos_state_next = (position + len_test + 1) & coder->pos_mask;
+
+			next_rep_match_price = cur_and_len_literal_price
+					+ rc_bit_1_price(coder->is_match[state_2][pos_state_next])
+					+ rc_bit_1_price(coder->is_rep[state_2]);
+
+			//for(; len_test_2 >= 2; len_test_2--) {
+			offset = cur + len_test + 1 + len_test_2;
+
+			while (len_end < offset)
+				coder->opts[++len_end].price = RC_INFINITY_PRICE;
+
+			cur_and_len_price = next_rep_match_price
+					+ get_rep_price(coder, 0, len_test_2,
+						state_2, pos_state_next);
+
+			if (cur_and_len_price < coder->opts[offset].price) {
+				coder->opts[offset].price = cur_and_len_price;
+				coder->opts[offset].pos_prev = cur + len_test + 1;
+				coder->opts[offset].back_prev = 0;
+				coder->opts[offset].prev_1_is_literal = true;
+				coder->opts[offset].prev_2 = true;
+				coder->opts[offset].pos_prev_2 = cur;
+				coder->opts[offset].back_prev_2 = rep_index;
+			}
+			//}
+		}
+	}
+
+
+	//for (uint32_t len_test = 2; len_test <= new_len; ++len_test)
+	if (new_len > buf_avail) {
+		new_len = buf_avail;
+
+		matches_count = 0;
+		while (new_len > coder->matches[matches_count].len)
+			++matches_count;
+
+		coder->matches[matches_count++].len = new_len;
+	}
+
+
+	if (new_len >= start_len) {
+		uint32_t len_test;
+		uint32_t i = 0;
+
+		const uint32_t normal_match_price = match_price
+				+ rc_bit_0_price(coder->is_rep[state]);
+
+		while (len_end < cur + new_len)
+			coder->opts[++len_end].price = RC_INFINITY_PRICE;
+
+		while (start_len > coder->matches[i].len)
+			++i;
+
+		for (len_test = start_len; ; ++len_test) {
+			const uint32_t cur_back = coder->matches[i].dist;
+			uint32_t cur_and_len_price = normal_match_price
+					+ get_pos_len_price(coder,
+						cur_back, len_test, pos_state);
+
+			if (cur_and_len_price < coder->opts[cur + len_test].price) {
+				coder->opts[cur + len_test].price = cur_and_len_price;
+				coder->opts[cur + len_test].pos_prev = cur;
+				coder->opts[cur + len_test].back_prev
+						= cur_back + REP_DISTANCES;
+				coder->opts[cur + len_test].prev_1_is_literal = false;
+			}
+
+			if (len_test == coder->matches[i].len) {
+				// Try Match + Literal + Rep0
+				const uint8_t *const buf_back = buf - cur_back - 1;
+				uint32_t len_test_2 = len_test + 1;
+				const uint32_t limit = my_min(buf_avail_full,
+						len_test_2 + nice_len);
+
+				for (; len_test_2 < limit &&
+						buf[len_test_2] == buf_back[len_test_2];
+						++len_test_2) ;
+
+				len_test_2 -= len_test + 1;
+
+				if (len_test_2 >= 2) {
+					uint32_t pos_state_next;
+					uint32_t cur_and_len_literal_price;
+					uint32_t next_rep_match_price;
+					uint32_t offset;
+
+					lzma_lzma_state state_2 = state;
+					update_match(state_2);
+					pos_state_next = (position + len_test) & coder->pos_mask;
+
+					cur_and_len_literal_price = cur_and_len_price
+							+ rc_bit_0_price(
+								coder->is_match[state_2][pos_state_next])
+							+ get_literal_price(coder,
+								position + len_test,
+								buf[len_test - 1],
+								true,
+								buf_back[len_test],
+								buf[len_test]);
+
+					update_literal(state_2);
+					pos_state_next = (pos_state_next + 1) & coder->pos_mask;
+
+					next_rep_match_price
+							= cur_and_len_literal_price
+							+ rc_bit_1_price(
+								coder->is_match[state_2][pos_state_next])
+							+ rc_bit_1_price(coder->is_rep[state_2]);
+
+					// for(; len_test_2 >= 2; --len_test_2) {
+					offset = cur + len_test + 1 + len_test_2;
+
+					while (len_end < offset)
+						coder->opts[++len_end].price = RC_INFINITY_PRICE;
+
+					cur_and_len_price = next_rep_match_price
+							+ get_rep_price(coder, 0, len_test_2,
+								state_2, pos_state_next);
+
+					if (cur_and_len_price < coder->opts[offset].price) {
+						coder->opts[offset].price = cur_and_len_price;
+						coder->opts[offset].pos_prev = cur + len_test + 1;
+						coder->opts[offset].back_prev = 0;
+						coder->opts[offset].prev_1_is_literal = true;
+						coder->opts[offset].prev_2 = true;
+						coder->opts[offset].pos_prev_2 = cur;
+						coder->opts[offset].back_prev_2
+								= cur_back + REP_DISTANCES;
+					}
+					//}
+				}
+
+				if (++i == matches_count)
+					break;
+			}
+		}
+	}
+
+	return len_end;
+}
+
+
+extern void
+lzma_lzma_optimum_normal(lzma_coder *LZMA_RESTRICT coder, lzma_mf *LZMA_RESTRICT mf,
+		uint32_t *LZMA_RESTRICT back_res, uint32_t *LZMA_RESTRICT len_res,
+		uint32_t position)
+{
+	uint32_t reps[REP_DISTANCES];
+	uint32_t len_end;
+	uint32_t cur;
+
+	// If we have symbols pending, return the next pending symbol.
+	if (coder->opts_end_index != coder->opts_current_index) {
+		assert(mf->read_ahead > 0);
+		*len_res = coder->opts[coder->opts_current_index].pos_prev
+				- coder->opts_current_index;
+		*back_res = coder->opts[coder->opts_current_index].back_prev;
+		coder->opts_current_index = coder->opts[
+				coder->opts_current_index].pos_prev;
+		return;
+	}
+
+	// Update the price tables. In LZMA SDK <= 4.60 (and possibly later)
+	// this was done in both initialization function and in the main loop.
+	// In liblzma they were moved into this single place.
+	if (mf->read_ahead == 0) {
+		if (coder->match_price_count >= (1 << 7))
+			fill_distances_prices(coder);
+
+		if (coder->align_price_count >= ALIGN_TABLE_SIZE)
+			fill_align_prices(coder);
+	}
+
+	// TODO: This needs quite a bit of cleaning still. But splitting
+	// the original function into two pieces makes it at least a little
+	// more readable, since those two parts don't share many variables.
+
+	len_end = helper1(coder, mf, back_res, len_res, position);
+	if (len_end == UINT32_MAX)
+		return;
+
+
+	memcpy(reps, coder->reps, sizeof(reps));
+
+	for (cur = 1; cur < len_end; ++cur) {
+		assert(cur < OPTS);
+
+		coder->longest_match_length = mf_find(
+				mf, &coder->matches_count, coder->matches);
+
+		if (coder->longest_match_length >= mf->nice_len)
+			break;
+
+		len_end = helper2(coder, reps, mf_ptr(mf) - 1, len_end,
+				position + cur, cur, mf->nice_len,
+				my_min(mf_avail(mf) + 1, OPTS - 1 - cur));
+	}
+
+	backward(coder, len_res, back_res, cur);
+	return;
+}
diff --git a/Utilities/cmliblzma/liblzma/lzma/lzma_encoder_presets.c b/Utilities/cmliblzma/liblzma/lzma/lzma_encoder_presets.c
new file mode 100644
index 0000000..8af9b9f
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/lzma/lzma_encoder_presets.c
@@ -0,0 +1,63 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       lzma_encoder_presets.c
+/// \brief      Encoder presets
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "common.h"
+
+
+extern LZMA_API(lzma_bool)
+lzma_lzma_preset(lzma_options_lzma *options, uint32_t preset)
+{
+	static const uint8_t dict_size_values[] = { 18, 20, 21, 22, 22, 23, 23, 24, 25, 26 };
+	static const uint8_t depth_values[] = { 4, 8, 24, 48 };
+
+	const uint32_t level = preset & LZMA_PRESET_LEVEL_MASK;
+	const uint32_t flags = preset & ~LZMA_PRESET_LEVEL_MASK;
+	const uint32_t supported_flags = LZMA_PRESET_EXTREME;
+
+	if (level > 9 || (flags & ~supported_flags))
+		return true;
+
+	options->preset_dict = NULL;
+	options->preset_dict_size = 0;
+
+	options->lc = LZMA_LC_DEFAULT;
+	options->lp = LZMA_LP_DEFAULT;
+	options->pb = LZMA_PB_DEFAULT;
+
+	options->dict_size = UINT32_C(1) << dict_size_values[level];
+
+	if (level <= 3) {
+		options->mode = LZMA_MODE_FAST;
+		options->mf = level == 0 ? LZMA_MF_HC3 : LZMA_MF_HC4;
+		options->nice_len = level <= 1 ? 128 : 273;
+		options->depth = depth_values[level];
+	} else {
+		options->mode = LZMA_MODE_NORMAL;
+		options->mf = LZMA_MF_BT4;
+		options->nice_len = level == 4 ? 16 : level == 5 ? 32 : 64;
+		options->depth = 0;
+	}
+
+	if (flags & LZMA_PRESET_EXTREME) {
+		options->mode = LZMA_MODE_NORMAL;
+		options->mf = LZMA_MF_BT4;
+		if (level == 3 || level == 5) {
+			options->nice_len = 192;
+			options->depth = 0;
+		} else {
+			options->nice_len = 273;
+			options->depth = 512;
+		}
+	}
+
+	return false;
+}
diff --git a/Utilities/cmliblzma/liblzma/lzma/lzma_encoder_private.h b/Utilities/cmliblzma/liblzma/lzma/lzma_encoder_private.h
new file mode 100644
index 0000000..04fb29e
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/lzma/lzma_encoder_private.h
@@ -0,0 +1,148 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       lzma_encoder_private.h
+/// \brief      Private definitions for LZMA encoder
+///
+//  Authors:    Igor Pavlov
+//              Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#ifndef LZMA_LZMA_ENCODER_PRIVATE_H
+#define LZMA_LZMA_ENCODER_PRIVATE_H
+
+#include "lz_encoder.h"
+#include "range_encoder.h"
+#include "lzma_common.h"
+#include "lzma_encoder.h"
+
+
+// Macro to compare if the first two bytes in two buffers differ. This is
+// needed in lzma_lzma_optimum_*() to test if the match is at least
+// MATCH_LEN_MIN bytes. Unaligned access gives tiny gain so there's no
+// reason to not use it when it is supported.
+#ifdef TUKLIB_FAST_UNALIGNED_ACCESS
+#	define not_equal_16(a, b) \
+		(*(const uint16_t *)(a) != *(const uint16_t *)(b))
+#else
+#	define not_equal_16(a, b) \
+		((a)[0] != (b)[0] || (a)[1] != (b)[1])
+#endif
+
+
+// Optimal - Number of entries in the optimum array.
+#define OPTS (1 << 12)
+
+
+typedef struct {
+	probability choice;
+	probability choice2;
+	probability low[POS_STATES_MAX][LEN_LOW_SYMBOLS];
+	probability mid[POS_STATES_MAX][LEN_MID_SYMBOLS];
+	probability high[LEN_HIGH_SYMBOLS];
+
+	uint32_t prices[POS_STATES_MAX][LEN_SYMBOLS];
+	uint32_t table_size;
+	uint32_t counters[POS_STATES_MAX];
+
+} lzma_length_encoder;
+
+
+typedef struct {
+	lzma_lzma_state state;
+
+	bool prev_1_is_literal;
+	bool prev_2;
+
+	uint32_t pos_prev_2;
+	uint32_t back_prev_2;
+
+	uint32_t price;
+	uint32_t pos_prev;  // pos_next;
+	uint32_t back_prev;
+
+	uint32_t backs[REP_DISTANCES];
+
+} lzma_optimal;
+
+
+struct lzma_coder_s {
+	/// Range encoder
+	lzma_range_encoder rc;
+
+	/// State
+	lzma_lzma_state state;
+
+	/// The four most recent match distances
+	uint32_t reps[REP_DISTANCES];
+
+	/// Array of match candidates
+	lzma_match matches[MATCH_LEN_MAX + 1];
+
+	/// Number of match candidates in matches[]
+	uint32_t matches_count;
+
+	/// Variable to hold the length of the longest match between calls
+	/// to lzma_lzma_optimum_*().
+	uint32_t longest_match_length;
+
+	/// True if using getoptimumfast
+	bool fast_mode;
+
+	/// True if the encoder has been initialized by encoding the first
+	/// byte as a literal.
+	bool is_initialized;
+
+	/// True if the range encoder has been flushed, but not all bytes
+	/// have been written to the output buffer yet.
+	bool is_flushed;
+
+	uint32_t pos_mask;         ///< (1 << pos_bits) - 1
+	uint32_t literal_context_bits;
+	uint32_t literal_pos_mask;
+
+	// These are the same as in lzma_decoder.c. See comments there.
+	probability literal[LITERAL_CODERS_MAX][LITERAL_CODER_SIZE];
+	probability is_match[STATES][POS_STATES_MAX];
+	probability is_rep[STATES];
+	probability is_rep0[STATES];
+	probability is_rep1[STATES];
+	probability is_rep2[STATES];
+	probability is_rep0_long[STATES][POS_STATES_MAX];
+	probability pos_slot[LEN_TO_POS_STATES][POS_SLOTS];
+	probability pos_special[FULL_DISTANCES - END_POS_MODEL_INDEX];
+	probability pos_align[ALIGN_TABLE_SIZE];
+
+	// These are the same as in lzma_decoder.c except that the encoders
+	// include also price tables.
+	lzma_length_encoder match_len_encoder;
+	lzma_length_encoder rep_len_encoder;
+
+	// Price tables
+	uint32_t pos_slot_prices[LEN_TO_POS_STATES][POS_SLOTS];
+	uint32_t distances_prices[LEN_TO_POS_STATES][FULL_DISTANCES];
+	uint32_t dist_table_size;
+	uint32_t match_price_count;
+
+	uint32_t align_prices[ALIGN_TABLE_SIZE];
+	uint32_t align_price_count;
+
+	// Optimal
+	uint32_t opts_end_index;
+	uint32_t opts_current_index;
+	lzma_optimal opts[OPTS];
+};
+
+
+extern void lzma_lzma_optimum_fast(
+		lzma_coder *LZMA_RESTRICT coder, lzma_mf *LZMA_RESTRICT mf,
+		uint32_t *LZMA_RESTRICT back_res, uint32_t *LZMA_RESTRICT len_res);
+
+extern void lzma_lzma_optimum_normal(lzma_coder *LZMA_RESTRICT coder,
+		lzma_mf *LZMA_RESTRICT mf, uint32_t *LZMA_RESTRICT back_res,
+		uint32_t *LZMA_RESTRICT len_res, uint32_t position);
+
+#endif
diff --git a/Utilities/cmliblzma/liblzma/rangecoder/price.h b/Utilities/cmliblzma/liblzma/rangecoder/price.h
new file mode 100644
index 0000000..8ae02ca
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/rangecoder/price.h
@@ -0,0 +1,92 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       price.h
+/// \brief      Probability price calculation
+//
+//  Author:     Igor Pavlov
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#ifndef LZMA_PRICE_H
+#define LZMA_PRICE_H
+
+
+#define RC_MOVE_REDUCING_BITS 4
+#define RC_BIT_PRICE_SHIFT_BITS 4
+#define RC_PRICE_TABLE_SIZE (RC_BIT_MODEL_TOTAL >> RC_MOVE_REDUCING_BITS)
+
+#define RC_INFINITY_PRICE (UINT32_C(1) << 30)
+
+
+/// Lookup table for the inline functions defined in this file.
+extern const uint8_t lzma_rc_prices[RC_PRICE_TABLE_SIZE];
+
+
+static inline uint32_t
+rc_bit_price(const probability prob, const uint32_t bit)
+{
+	return lzma_rc_prices[(prob ^ ((UINT32_C(0) - bit)
+			& (RC_BIT_MODEL_TOTAL - 1))) >> RC_MOVE_REDUCING_BITS];
+}
+
+
+static inline uint32_t
+rc_bit_0_price(const probability prob)
+{
+	return lzma_rc_prices[prob >> RC_MOVE_REDUCING_BITS];
+}
+
+
+static inline uint32_t
+rc_bit_1_price(const probability prob)
+{
+	return lzma_rc_prices[(prob ^ (RC_BIT_MODEL_TOTAL - 1))
+			>> RC_MOVE_REDUCING_BITS];
+}
+
+
+static inline uint32_t
+rc_bittree_price(const probability *const probs,
+		const uint32_t bit_levels, uint32_t symbol)
+{
+	uint32_t price = 0;
+	symbol += UINT32_C(1) << bit_levels;
+
+	do {
+		const uint32_t bit = symbol & 1;
+		symbol >>= 1;
+		price += rc_bit_price(probs[symbol], bit);
+	} while (symbol != 1);
+
+	return price;
+}
+
+
+static inline uint32_t
+rc_bittree_reverse_price(const probability *const probs,
+		uint32_t bit_levels, uint32_t symbol)
+{
+	uint32_t price = 0;
+	uint32_t model_index = 1;
+
+	do {
+		const uint32_t bit = symbol & 1;
+		symbol >>= 1;
+		price += rc_bit_price(probs[model_index], bit);
+		model_index = (model_index << 1) + bit;
+	} while (--bit_levels != 0);
+
+	return price;
+}
+
+
+static inline uint32_t
+rc_direct_price(const uint32_t bits)
+{
+	 return bits << RC_BIT_PRICE_SHIFT_BITS;
+}
+
+#endif
diff --git a/Utilities/cmliblzma/liblzma/rangecoder/price_table.c b/Utilities/cmliblzma/liblzma/rangecoder/price_table.c
new file mode 100644
index 0000000..ac64bf6
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/rangecoder/price_table.c
@@ -0,0 +1,22 @@
+/* This file has been automatically generated by price_tablegen.c. */
+
+#include "range_encoder.h"
+
+const uint8_t lzma_rc_prices[RC_PRICE_TABLE_SIZE] = {
+	 128, 103,  91,  84,  78,  73,  69,  66,
+	  63,  61,  58,  56,  54,  52,  51,  49,
+	  48,  46,  45,  44,  43,  42,  41,  40,
+	  39,  38,  37,  36,  35,  34,  34,  33,
+	  32,  31,  31,  30,  29,  29,  28,  28,
+	  27,  26,  26,  25,  25,  24,  24,  23,
+	  23,  22,  22,  22,  21,  21,  20,  20,
+	  19,  19,  19,  18,  18,  17,  17,  17,
+	  16,  16,  16,  15,  15,  15,  14,  14,
+	  14,  13,  13,  13,  12,  12,  12,  11,
+	  11,  11,  11,  10,  10,  10,  10,   9,
+	   9,   9,   9,   8,   8,   8,   8,   7,
+	   7,   7,   7,   6,   6,   6,   6,   5,
+	   5,   5,   5,   5,   4,   4,   4,   4,
+	   3,   3,   3,   3,   3,   2,   2,   2,
+	   2,   2,   2,   1,   1,   1,   1,   1
+};
diff --git a/Utilities/cmliblzma/liblzma/rangecoder/price_tablegen.c b/Utilities/cmliblzma/liblzma/rangecoder/price_tablegen.c
new file mode 100644
index 0000000..bf08ce3
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/rangecoder/price_tablegen.c
@@ -0,0 +1,87 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       price_tablegen.c
+/// \brief      Probability price table generator
+///
+/// Compiling: gcc -std=c99 -o price_tablegen price_tablegen.c
+///
+//  Authors:    Igor Pavlov
+//              Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include <inttypes.h>
+#include <stdio.h>
+#include "range_common.h"
+#include "price.h"
+
+
+static uint32_t rc_prices[RC_PRICE_TABLE_SIZE];
+
+
+static void
+init_price_table(void)
+{
+	for (uint32_t i = (UINT32_C(1) << RC_MOVE_REDUCING_BITS) / 2;
+			i < RC_BIT_MODEL_TOTAL;
+			i += (UINT32_C(1) << RC_MOVE_REDUCING_BITS)) {
+		const uint32_t cycles_bits = RC_BIT_PRICE_SHIFT_BITS;
+		uint32_t w = i;
+		uint32_t bit_count = 0;
+
+		for (uint32_t j = 0; j < cycles_bits; ++j) {
+			w *= w;
+			bit_count <<= 1;
+
+			while (w >= (UINT32_C(1) << 16)) {
+				w >>= 1;
+				++bit_count;
+			}
+		}
+
+		rc_prices[i >> RC_MOVE_REDUCING_BITS]
+				= (RC_BIT_MODEL_TOTAL_BITS << cycles_bits)
+				- 15 - bit_count;
+	}
+
+	return;
+}
+
+
+static void
+print_price_table(void)
+{
+	printf("/* This file has been automatically generated by "
+			"price_tablegen.c. */\n\n"
+			"#include \"range_encoder.h\"\n\n"
+			"const uint8_t lzma_rc_prices["
+			"RC_PRICE_TABLE_SIZE] = {");
+
+	const size_t array_size = sizeof(lzma_rc_prices)
+			/ sizeof(lzma_rc_prices[0]);
+	for (size_t i = 0; i < array_size; ++i) {
+		if (i % 8 == 0)
+			printf("\n\t");
+
+		printf("%4" PRIu32, rc_prices[i]);
+
+		if (i != array_size - 1)
+			printf(",");
+	}
+
+	printf("\n};\n");
+
+	return;
+}
+
+
+int
+main(void)
+{
+	init_price_table();
+	print_price_table();
+	return 0;
+}
diff --git a/Utilities/cmliblzma/liblzma/rangecoder/range_common.h b/Utilities/cmliblzma/liblzma/rangecoder/range_common.h
new file mode 100644
index 0000000..f15623e
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/rangecoder/range_common.h
@@ -0,0 +1,74 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       range_common.h
+/// \brief      Common things for range encoder and decoder
+///
+//  Authors:    Igor Pavlov
+//              Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#ifndef LZMA_RANGE_COMMON_H
+#define LZMA_RANGE_COMMON_H
+
+#include "common.h"
+
+
+///////////////
+// Constants //
+///////////////
+
+#define RC_SHIFT_BITS 8
+#define RC_TOP_BITS 24
+#define RC_TOP_VALUE (UINT32_C(1) << RC_TOP_BITS)
+#define RC_BIT_MODEL_TOTAL_BITS 11
+#define RC_BIT_MODEL_TOTAL (UINT32_C(1) << RC_BIT_MODEL_TOTAL_BITS)
+#define RC_MOVE_BITS 5
+
+
+////////////
+// Macros //
+////////////
+
+// Resets the probability so that both 0 and 1 have probability of 50 %
+#define bit_reset(prob) \
+	prob = RC_BIT_MODEL_TOTAL >> 1
+
+// This does the same for a complete bit tree.
+// (A tree represented as an array.)
+#define bittree_reset(probs, bit_levels) \
+	do { \
+		uint32_t bt_i; \
+		for (bt_i = 0; bt_i < (1 << (bit_levels)); ++bt_i) \
+			bit_reset((probs)[bt_i]); \
+	} while (0)
+
+
+//////////////////////
+// Type definitions //
+//////////////////////
+
+/// \brief      Type of probabilities used with range coder
+///
+/// This needs to be at least 12-bit integer, so uint16_t is a logical choice.
+/// However, on some architecture and compiler combinations, a bigger type
+/// may give better speed, because the probability variables are accessed
+/// a lot. On the other hand, bigger probability type increases cache
+/// footprint, since there are 2 to 14 thousand probability variables in
+/// LZMA (assuming the limit of lc + lp <= 4; with lc + lp <= 12 there
+/// would be about 1.5 million variables).
+///
+/// With malicious files, the initialization speed of the LZMA decoder can
+/// become important. In that case, smaller probability variables mean that
+/// there is less bytes to write to RAM, which makes initialization faster.
+/// With big probability type, the initialization can become so slow that it
+/// can be a problem e.g. for email servers doing virus scanning.
+///
+/// I will be sticking to uint16_t unless some specific architectures
+/// are *much* faster (20-50 %) with uint32_t.
+typedef uint16_t probability;
+
+#endif
diff --git a/Utilities/cmliblzma/liblzma/rangecoder/range_decoder.h b/Utilities/cmliblzma/liblzma/rangecoder/range_decoder.h
new file mode 100644
index 0000000..199e7b5
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/rangecoder/range_decoder.h
@@ -0,0 +1,179 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       range_decoder.h
+/// \brief      Range Decoder
+///
+//  Authors:    Igor Pavlov
+//              Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#ifndef LZMA_RANGE_DECODER_H
+#define LZMA_RANGE_DECODER_H
+
+#include "range_common.h"
+
+
+typedef struct {
+	uint32_t range;
+	uint32_t code;
+	uint32_t init_bytes_left;
+} lzma_range_decoder;
+
+
+/// Reads the first five bytes to initialize the range decoder.
+static inline bool
+rc_read_init(lzma_range_decoder *rc, const uint8_t *LZMA_RESTRICT in,
+		size_t *LZMA_RESTRICT in_pos, size_t in_size)
+{
+	while (rc->init_bytes_left > 0) {
+		if (*in_pos == in_size)
+			return false;
+
+		rc->code = (rc->code << 8) | in[*in_pos];
+		++*in_pos;
+		--rc->init_bytes_left;
+	}
+
+	return true;
+}
+
+
+/// Makes local copies of range decoder and *in_pos variables. Doing this
+/// improves speed significantly. The range decoder macros expect also
+/// variables `in' and `in_size' to be defined.
+#define rc_to_local(range_decoder, in_pos) \
+	lzma_range_decoder rc = range_decoder; \
+	size_t rc_in_pos = (in_pos); \
+	uint32_t rc_bound
+
+
+/// Stores the local copes back to the range decoder structure.
+#define rc_from_local(range_decoder, in_pos) \
+do { \
+	range_decoder = rc; \
+	in_pos = rc_in_pos; \
+} while (0)
+
+
+/// Resets the range decoder structure.
+#define rc_reset(range_decoder) \
+do { \
+	(range_decoder).range = UINT32_MAX; \
+	(range_decoder).code = 0; \
+	(range_decoder).init_bytes_left = 5; \
+} while (0)
+
+
+/// When decoding has been properly finished, rc.code is always zero unless
+/// the input stream is corrupt. So checking this can catch some corrupt
+/// files especially if they don't have any other integrity check.
+#define rc_is_finished(range_decoder) \
+	((range_decoder).code == 0)
+
+
+/// Read the next input byte if needed. If more input is needed but there is
+/// no more input available, "goto out" is used to jump out of the main
+/// decoder loop.
+#define rc_normalize(seq) \
+do { \
+	if (rc.range < RC_TOP_VALUE) { \
+		if (unlikely(rc_in_pos == in_size)) { \
+			coder->sequence = seq; \
+			goto out; \
+		} \
+		rc.range <<= RC_SHIFT_BITS; \
+		rc.code = (rc.code << RC_SHIFT_BITS) | in[rc_in_pos++]; \
+	} \
+} while (0)
+
+
+/// Start decoding a bit. This must be used together with rc_update_0()
+/// and rc_update_1():
+///
+///     rc_if_0(prob, seq) {
+///         rc_update_0(prob);
+///         // Do something
+///     } else {
+///         rc_update_1(prob);
+///         // Do something else
+///     }
+///
+#define rc_if_0(prob, seq) \
+	rc_normalize(seq); \
+	rc_bound = (rc.range >> RC_BIT_MODEL_TOTAL_BITS) * (prob); \
+	if (rc.code < rc_bound)
+
+
+/// Update the range decoder state and the used probability variable to
+/// match a decoded bit of 0.
+#define rc_update_0(prob) \
+do { \
+	rc.range = rc_bound; \
+	prob += (RC_BIT_MODEL_TOTAL - (prob)) >> RC_MOVE_BITS; \
+} while (0)
+
+
+/// Update the range decoder state and the used probability variable to
+/// match a decoded bit of 1.
+#define rc_update_1(prob) \
+do { \
+	rc.range -= rc_bound; \
+	rc.code -= rc_bound; \
+	prob -= (prob) >> RC_MOVE_BITS; \
+} while (0)
+
+
+/// Decodes one bit and runs action0 or action1 depending on the decoded bit.
+/// This macro is used as the last step in bittree reverse decoders since
+/// those don't use "symbol" for anything else than indexing the probability
+/// arrays.
+#define rc_bit_last(prob, action0, action1, seq) \
+do { \
+	rc_if_0(prob, seq) { \
+		rc_update_0(prob); \
+		action0; \
+	} else { \
+		rc_update_1(prob); \
+		action1; \
+	} \
+} while (0)
+
+
+/// Decodes one bit, updates "symbol", and runs action0 or action1 depending
+/// on the decoded bit.
+#define rc_bit(prob, action0, action1, seq) \
+	rc_bit_last(prob, \
+		symbol <<= 1; action0, \
+		symbol = (symbol << 1) + 1; action1, \
+		seq);
+
+
+/// Like rc_bit() but add "case seq:" as a prefix. This makes the unrolled
+/// loops more readable because the code isn't littered with "case"
+/// statements. On the other hand this also makes it less readable, since
+/// spotting the places where the decoder loop may be restarted is less
+/// obvious.
+#define rc_bit_case(prob, action0, action1, seq) \
+	case seq: rc_bit(prob, action0, action1, seq)
+
+
+/// Decode a bit without using a probability.
+#define rc_direct(dest, seq) \
+do { \
+	rc_normalize(seq); \
+	rc.range >>= 1; \
+	rc.code -= rc.range; \
+	rc_bound = UINT32_C(0) - (rc.code >> 31); \
+	rc.code += rc.range & rc_bound; \
+	dest = (dest << 1) + (rc_bound + 1); \
+} while (0)
+
+
+// NOTE: No macros are provided for bittree decoding. It seems to be simpler
+// to just write them open in the code.
+
+#endif
diff --git a/Utilities/cmliblzma/liblzma/rangecoder/range_encoder.h b/Utilities/cmliblzma/liblzma/rangecoder/range_encoder.h
new file mode 100644
index 0000000..e9614f2
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/rangecoder/range_encoder.h
@@ -0,0 +1,232 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       range_encoder.h
+/// \brief      Range Encoder
+///
+//  Authors:    Igor Pavlov
+//              Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#ifndef LZMA_RANGE_ENCODER_H
+#define LZMA_RANGE_ENCODER_H
+
+#include "range_common.h"
+#include "price.h"
+
+
+/// Maximum number of symbols that can be put pending into lzma_range_encoder
+/// structure between calls to lzma_rc_encode(). For LZMA, 52+5 is enough
+/// (match with big distance and length followed by range encoder flush).
+#define RC_SYMBOLS_MAX 58
+
+
+typedef struct {
+	uint64_t low;
+	uint64_t cache_size;
+	uint32_t range;
+	uint8_t cache;
+
+	/// Number of symbols in the tables
+	size_t count;
+
+	/// rc_encode()'s position in the tables
+	size_t pos;
+
+	/// Symbols to encode
+	enum {
+		RC_BIT_0,
+		RC_BIT_1,
+		RC_DIRECT_0,
+		RC_DIRECT_1,
+		RC_FLUSH,
+	} symbols[RC_SYMBOLS_MAX];
+
+	/// Probabilities associated with RC_BIT_0 or RC_BIT_1
+	probability *probs[RC_SYMBOLS_MAX];
+
+} lzma_range_encoder;
+
+
+static inline void
+rc_reset(lzma_range_encoder *rc)
+{
+	rc->low = 0;
+	rc->cache_size = 1;
+	rc->range = UINT32_MAX;
+	rc->cache = 0;
+	rc->count = 0;
+	rc->pos = 0;
+}
+
+
+static inline void
+rc_bit(lzma_range_encoder *rc, probability *prob, uint32_t bit)
+{
+	rc->symbols[rc->count] = bit;
+	rc->probs[rc->count] = prob;
+	++rc->count;
+}
+
+
+static inline void
+rc_bittree(lzma_range_encoder *rc, probability *probs,
+		uint32_t bit_count, uint32_t symbol)
+{
+	uint32_t model_index = 1;
+
+	do {
+		const uint32_t bit = (symbol >> --bit_count) & 1;
+		rc_bit(rc, &probs[model_index], bit);
+		model_index = (model_index << 1) + bit;
+	} while (bit_count != 0);
+}
+
+
+static inline void
+rc_bittree_reverse(lzma_range_encoder *rc, probability *probs,
+		uint32_t bit_count, uint32_t symbol)
+{
+	uint32_t model_index = 1;
+
+	do {
+		const uint32_t bit = symbol & 1;
+		symbol >>= 1;
+		rc_bit(rc, &probs[model_index], bit);
+		model_index = (model_index << 1) + bit;
+	} while (--bit_count != 0);
+}
+
+
+static inline void
+rc_direct(lzma_range_encoder *rc,
+		uint32_t value, uint32_t bit_count)
+{
+	do {
+		rc->symbols[rc->count++]
+				= RC_DIRECT_0 + ((value >> --bit_count) & 1);
+	} while (bit_count != 0);
+}
+
+
+static inline void
+rc_flush(lzma_range_encoder *rc)
+{
+	size_t i;
+	for (i = 0; i < 5; ++i)
+		rc->symbols[rc->count++] = RC_FLUSH;
+}
+
+
+static inline bool
+rc_shift_low(lzma_range_encoder *rc,
+		uint8_t *out, size_t *out_pos, size_t out_size)
+{
+	if ((uint32_t)(rc->low) < (uint32_t)(0xFF000000)
+			|| (uint32_t)(rc->low >> 32) != 0) {
+		do {
+			if (*out_pos == out_size)
+				return true;
+
+			out[*out_pos] = rc->cache + (uint8_t)(rc->low >> 32);
+			++*out_pos;
+			rc->cache = 0xFF;
+
+		} while (--rc->cache_size != 0);
+
+		rc->cache = (rc->low >> 24) & 0xFF;
+	}
+
+	++rc->cache_size;
+	rc->low = (rc->low & 0x00FFFFFF) << RC_SHIFT_BITS;
+
+	return false;
+}
+
+
+static inline bool
+rc_encode(lzma_range_encoder *rc,
+		uint8_t *out, size_t *out_pos, size_t out_size)
+{
+	assert(rc->count <= RC_SYMBOLS_MAX);
+
+	while (rc->pos < rc->count) {
+		// Normalize
+		if (rc->range < RC_TOP_VALUE) {
+			if (rc_shift_low(rc, out, out_pos, out_size))
+				return true;
+
+			rc->range <<= RC_SHIFT_BITS;
+		}
+
+		// Encode a bit
+		switch (rc->symbols[rc->pos]) {
+		case RC_BIT_0: {
+			probability prob = *rc->probs[rc->pos];
+			rc->range = (rc->range >> RC_BIT_MODEL_TOTAL_BITS)
+					* prob;
+			prob += (RC_BIT_MODEL_TOTAL - prob) >> RC_MOVE_BITS;
+			*rc->probs[rc->pos] = prob;
+			break;
+		}
+
+		case RC_BIT_1: {
+			probability prob = *rc->probs[rc->pos];
+			const uint32_t bound = prob * (rc->range
+					>> RC_BIT_MODEL_TOTAL_BITS);
+			rc->low += bound;
+			rc->range -= bound;
+			prob -= prob >> RC_MOVE_BITS;
+			*rc->probs[rc->pos] = prob;
+			break;
+		}
+
+		case RC_DIRECT_0:
+			rc->range >>= 1;
+			break;
+
+		case RC_DIRECT_1:
+			rc->range >>= 1;
+			rc->low += rc->range;
+			break;
+
+		case RC_FLUSH:
+			// Prevent further normalizations.
+			rc->range = UINT32_MAX;
+
+			// Flush the last five bytes (see rc_flush()).
+			do {
+				if (rc_shift_low(rc, out, out_pos, out_size))
+					return true;
+			} while (++rc->pos < rc->count);
+
+			// Reset the range encoder so we are ready to continue
+			// encoding if we weren't finishing the stream.
+			rc_reset(rc);
+			return false;
+
+		default:
+			assert(0);
+			break;
+		}
+
+		++rc->pos;
+	}
+
+	rc->count = 0;
+	rc->pos = 0;
+
+	return false;
+}
+
+
+static inline uint64_t
+rc_pending(const lzma_range_encoder *rc)
+{
+	return rc->cache_size + 5 - 1;
+}
+
+#endif
diff --git a/Utilities/cmliblzma/liblzma/simple/arm.c b/Utilities/cmliblzma/liblzma/simple/arm.c
new file mode 100644
index 0000000..8dcba39
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/simple/arm.c
@@ -0,0 +1,69 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       arm.c
+/// \brief      Filter for ARM binaries
+///
+//  Authors:    Igor Pavlov
+//              Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "simple_private.h"
+
+
+static size_t
+arm_code(lzma_simple *simple lzma_attribute((__unused__)),
+		uint32_t now_pos, bool is_encoder,
+		uint8_t *buffer, size_t size)
+{
+	size_t i;
+	for (i = 0; i + 4 <= size; i += 4) {
+		if (buffer[i + 3] == 0xEB) {
+			uint32_t dest;
+			uint32_t src = (buffer[i + 2] << 16)
+					| (buffer[i + 1] << 8)
+					| (buffer[i + 0]);
+			src <<= 2;
+
+			if (is_encoder)
+				dest = now_pos + (uint32_t)(i) + 8 + src;
+			else
+				dest = src - (now_pos + (uint32_t)(i) + 8);
+
+			dest >>= 2;
+			buffer[i + 2] = (dest >> 16);
+			buffer[i + 1] = (dest >> 8);
+			buffer[i + 0] = dest;
+		}
+	}
+
+	return i;
+}
+
+
+static lzma_ret
+arm_coder_init(lzma_next_coder *next, lzma_allocator *allocator,
+		const lzma_filter_info *filters, bool is_encoder)
+{
+	return lzma_simple_coder_init(next, allocator, filters,
+			&arm_code, 0, 4, 4, is_encoder);
+}
+
+
+extern lzma_ret
+lzma_simple_arm_encoder_init(lzma_next_coder *next, lzma_allocator *allocator,
+		const lzma_filter_info *filters)
+{
+	return arm_coder_init(next, allocator, filters, true);
+}
+
+
+extern lzma_ret
+lzma_simple_arm_decoder_init(lzma_next_coder *next, lzma_allocator *allocator,
+		const lzma_filter_info *filters)
+{
+	return arm_coder_init(next, allocator, filters, false);
+}
diff --git a/Utilities/cmliblzma/liblzma/simple/armthumb.c b/Utilities/cmliblzma/liblzma/simple/armthumb.c
new file mode 100644
index 0000000..4b890a3
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/simple/armthumb.c
@@ -0,0 +1,74 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       armthumb.c
+/// \brief      Filter for ARM-Thumb binaries
+///
+//  Authors:    Igor Pavlov
+//              Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "simple_private.h"
+
+
+static size_t
+armthumb_code(lzma_simple *simple lzma_attribute((__unused__)),
+		uint32_t now_pos, bool is_encoder,
+		uint8_t *buffer, size_t size)
+{
+	size_t i;
+	for (i = 0; i + 4 <= size; i += 2) {
+		if ((buffer[i + 1] & 0xF8) == 0xF0
+				&& (buffer[i + 3] & 0xF8) == 0xF8) {
+			uint32_t dest;
+			uint32_t src = ((buffer[i + 1] & 0x7) << 19)
+					| (buffer[i + 0] << 11)
+					| ((buffer[i + 3] & 0x7) << 8)
+					| (buffer[i + 2]);
+
+			src <<= 1;
+
+			if (is_encoder)
+				dest = now_pos + (uint32_t)(i) + 4 + src;
+			else
+				dest = src - (now_pos + (uint32_t)(i) + 4);
+
+			dest >>= 1;
+			buffer[i + 1] = 0xF0 | ((dest >> 19) & 0x7);
+			buffer[i + 0] = (dest >> 11);
+			buffer[i + 3] = 0xF8 | ((dest >> 8) & 0x7);
+			buffer[i + 2] = (dest);
+			i += 2;
+		}
+	}
+
+	return i;
+}
+
+
+static lzma_ret
+armthumb_coder_init(lzma_next_coder *next, lzma_allocator *allocator,
+		const lzma_filter_info *filters, bool is_encoder)
+{
+	return lzma_simple_coder_init(next, allocator, filters,
+			&armthumb_code, 0, 4, 2, is_encoder);
+}
+
+
+extern lzma_ret
+lzma_simple_armthumb_encoder_init(lzma_next_coder *next,
+		lzma_allocator *allocator, const lzma_filter_info *filters)
+{
+	return armthumb_coder_init(next, allocator, filters, true);
+}
+
+
+extern lzma_ret
+lzma_simple_armthumb_decoder_init(lzma_next_coder *next,
+		lzma_allocator *allocator, const lzma_filter_info *filters)
+{
+	return armthumb_coder_init(next, allocator, filters, false);
+}
diff --git a/Utilities/cmliblzma/liblzma/simple/ia64.c b/Utilities/cmliblzma/liblzma/simple/ia64.c
new file mode 100644
index 0000000..c537cac
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/simple/ia64.c
@@ -0,0 +1,116 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       ia64.c
+/// \brief      Filter for IA64 (Itanium) binaries
+///
+//  Authors:    Igor Pavlov
+//              Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "simple_private.h"
+
+
+static size_t
+ia64_code(lzma_simple *simple lzma_attribute((__unused__)),
+		uint32_t now_pos, bool is_encoder,
+		uint8_t *buffer, size_t size)
+{
+	static const uint32_t BRANCH_TABLE[32] = {
+		0, 0, 0, 0, 0, 0, 0, 0,
+		0, 0, 0, 0, 0, 0, 0, 0,
+		4, 4, 6, 6, 0, 0, 7, 7,
+		4, 4, 0, 0, 4, 4, 0, 0
+	};
+
+	size_t i;
+	for (i = 0; i + 16 <= size; i += 16) {
+		size_t slot;
+
+		const uint32_t instr_template = buffer[i] & 0x1F;
+		const uint32_t mask = BRANCH_TABLE[instr_template];
+		uint32_t bit_pos = 5;
+
+		for (slot = 0; slot < 3; ++slot, bit_pos += 41) {
+			const size_t byte_pos = (bit_pos >> 3);
+			const uint32_t bit_res = bit_pos & 0x7;
+			uint64_t instruction = 0;
+			uint64_t inst_norm;
+			size_t j;
+
+			if (((mask >> slot) & 1) == 0)
+				continue;
+
+			for (j = 0; j < 6; ++j)
+				instruction += (uint64_t)(
+						buffer[i + j + byte_pos])
+						<< (8 * j);
+
+			inst_norm = instruction >> bit_res;
+
+			if (((inst_norm >> 37) & 0xF) == 0x5
+					&& ((inst_norm >> 9) & 0x7) == 0
+					/* &&  (inst_norm & 0x3F)== 0 */
+					) {
+				uint32_t dest;
+				size_t j;
+
+				uint32_t src = (uint32_t)(
+						(inst_norm >> 13) & 0xFFFFF);
+				src |= ((inst_norm >> 36) & 1) << 20;
+
+				src <<= 4;
+
+				if (is_encoder)
+					dest = now_pos + (uint32_t)(i) + src;
+				else
+					dest = src - (now_pos + (uint32_t)(i));
+
+				dest >>= 4;
+
+				inst_norm &= ~((uint64_t)(0x8FFFFF) << 13);
+				inst_norm |= (uint64_t)(dest & 0xFFFFF) << 13;
+				inst_norm |= (uint64_t)(dest & 0x100000)
+						<< (36 - 20);
+
+				instruction &= (1 << bit_res) - 1;
+				instruction |= (inst_norm << bit_res);
+
+				for (j = 0; j < 6; j++)
+					buffer[i + j + byte_pos] = (uint8_t)(
+							instruction
+							>> (8 * j));
+			}
+		}
+	}
+
+	return i;
+}
+
+
+static lzma_ret
+ia64_coder_init(lzma_next_coder *next, lzma_allocator *allocator,
+		const lzma_filter_info *filters, bool is_encoder)
+{
+	return lzma_simple_coder_init(next, allocator, filters,
+			&ia64_code, 0, 16, 16, is_encoder);
+}
+
+
+extern lzma_ret
+lzma_simple_ia64_encoder_init(lzma_next_coder *next,
+		lzma_allocator *allocator, const lzma_filter_info *filters)
+{
+	return ia64_coder_init(next, allocator, filters, true);
+}
+
+
+extern lzma_ret
+lzma_simple_ia64_decoder_init(lzma_next_coder *next,
+		lzma_allocator *allocator, const lzma_filter_info *filters)
+{
+	return ia64_coder_init(next, allocator, filters, false);
+}
diff --git a/Utilities/cmliblzma/liblzma/simple/powerpc.c b/Utilities/cmliblzma/liblzma/simple/powerpc.c
new file mode 100644
index 0000000..6f83511
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/simple/powerpc.c
@@ -0,0 +1,73 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       powerpc.c
+/// \brief      Filter for PowerPC (big endian) binaries
+///
+//  Authors:    Igor Pavlov
+//              Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "simple_private.h"
+
+
+static size_t
+powerpc_code(lzma_simple *simple lzma_attribute((__unused__)),
+		uint32_t now_pos, bool is_encoder,
+		uint8_t *buffer, size_t size)
+{
+	size_t i;
+	for (i = 0; i + 4 <= size; i += 4) {
+		// PowerPC branch 6(48) 24(Offset) 1(Abs) 1(Link)
+		if ((buffer[i] >> 2) == 0x12
+				&& ((buffer[i + 3] & 3) == 1)) {
+
+			const uint32_t src = ((buffer[i + 0] & 3) << 24)
+					| (buffer[i + 1] << 16)
+					| (buffer[i + 2] << 8)
+					| (buffer[i + 3] & (~3));
+
+			uint32_t dest;
+			if (is_encoder)
+				dest = now_pos + (uint32_t)(i) + src;
+			else
+				dest = src - (now_pos + (uint32_t)(i));
+
+			buffer[i + 0] = 0x48 | ((dest >> 24) &  0x03);
+			buffer[i + 1] = (dest >> 16);
+			buffer[i + 2] = (dest >> 8);
+			buffer[i + 3] &= 0x03;
+			buffer[i + 3] |= dest;
+		}
+	}
+
+	return i;
+}
+
+
+static lzma_ret
+powerpc_coder_init(lzma_next_coder *next, lzma_allocator *allocator,
+		const lzma_filter_info *filters, bool is_encoder)
+{
+	return lzma_simple_coder_init(next, allocator, filters,
+			&powerpc_code, 0, 4, 4, is_encoder);
+}
+
+
+extern lzma_ret
+lzma_simple_powerpc_encoder_init(lzma_next_coder *next,
+		lzma_allocator *allocator, const lzma_filter_info *filters)
+{
+	return powerpc_coder_init(next, allocator, filters, true);
+}
+
+
+extern lzma_ret
+lzma_simple_powerpc_decoder_init(lzma_next_coder *next,
+		lzma_allocator *allocator, const lzma_filter_info *filters)
+{
+	return powerpc_coder_init(next, allocator, filters, false);
+}
diff --git a/Utilities/cmliblzma/liblzma/simple/simple_coder.c b/Utilities/cmliblzma/liblzma/simple/simple_coder.c
new file mode 100644
index 0000000..f3bbdd7
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/simple/simple_coder.c
@@ -0,0 +1,283 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       simple_coder.c
+/// \brief      Wrapper for simple filters
+///
+/// Simple filters don't change the size of the data i.e. number of bytes
+/// in equals the number of bytes out.
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "simple_private.h"
+
+
+/// Copied or encodes/decodes more data to out[].
+static lzma_ret
+copy_or_code(lzma_coder *coder, lzma_allocator *allocator,
+		const uint8_t *LZMA_RESTRICT in, size_t *LZMA_RESTRICT in_pos,
+		size_t in_size, uint8_t *LZMA_RESTRICT out,
+		size_t *LZMA_RESTRICT out_pos, size_t out_size, lzma_action action)
+{
+	assert(!coder->end_was_reached);
+
+	if (coder->next.code == NULL) {
+		lzma_bufcpy(in, in_pos, in_size, out, out_pos, out_size);
+
+		// Check if end of stream was reached.
+		if (coder->is_encoder && action == LZMA_FINISH
+				&& *in_pos == in_size)
+			coder->end_was_reached = true;
+
+	} else {
+		// Call the next coder in the chain to provide us some data.
+		const lzma_ret ret = coder->next.code(
+				coder->next.coder, allocator,
+				in, in_pos, in_size,
+				out, out_pos, out_size, action);
+
+		if (ret == LZMA_STREAM_END) {
+			assert(!coder->is_encoder
+					|| action == LZMA_FINISH);
+			coder->end_was_reached = true;
+
+		} else if (ret != LZMA_OK) {
+			return ret;
+		}
+	}
+
+	return LZMA_OK;
+}
+
+
+static size_t
+call_filter(lzma_coder *coder, uint8_t *buffer, size_t size)
+{
+	const size_t filtered = coder->filter(coder->simple,
+			coder->now_pos, coder->is_encoder,
+			buffer, size);
+	coder->now_pos += filtered;
+	return filtered;
+}
+
+
+static lzma_ret
+simple_code(lzma_coder *coder, lzma_allocator *allocator,
+		const uint8_t *LZMA_RESTRICT in, size_t *LZMA_RESTRICT in_pos,
+		size_t in_size, uint8_t *LZMA_RESTRICT out,
+		size_t *LZMA_RESTRICT out_pos, size_t out_size, lzma_action action)
+{
+	size_t out_avail;
+	size_t buf_avail;
+
+	// TODO: Add partial support for LZMA_SYNC_FLUSH. We can support it
+	// in cases when the filter is able to filter everything. With most
+	// simple filters it can be done at offset that is a multiple of 2,
+	// 4, or 16. With x86 filter, it needs good luck, and thus cannot
+	// be made to work predictably.
+	if (action == LZMA_SYNC_FLUSH)
+		return LZMA_OPTIONS_ERROR;
+
+	// Flush already filtered data from coder->buffer[] to out[].
+	if (coder->pos < coder->filtered) {
+		lzma_bufcpy(coder->buffer, &coder->pos, coder->filtered,
+				out, out_pos, out_size);
+
+		// If we couldn't flush all the filtered data, return to
+		// application immediately.
+		if (coder->pos < coder->filtered)
+			return LZMA_OK;
+
+		if (coder->end_was_reached) {
+			assert(coder->filtered == coder->size);
+			return LZMA_STREAM_END;
+		}
+	}
+
+	// If we get here, there is no filtered data left in the buffer.
+	coder->filtered = 0;
+
+	assert(!coder->end_was_reached);
+
+	// If there is more output space left than there is unfiltered data
+	// in coder->buffer[], flush coder->buffer[] to out[], and copy/code
+	// more data to out[] hopefully filling it completely. Then filter
+	// the data in out[]. This step is where most of the data gets
+	// filtered if the buffer sizes used by the application are reasonable.
+	out_avail = out_size - *out_pos;
+	buf_avail = coder->size - coder->pos;
+	if (out_avail > buf_avail || buf_avail == 0) {
+		size_t size;
+		size_t filtered;
+		size_t unfiltered;
+
+		// Store the old position so that we know from which byte
+		// to start filtering.
+		const size_t out_start = *out_pos;
+
+		// Flush data from coder->buffer[] to out[], but don't reset
+		// coder->pos and coder->size yet. This way the coder can be
+		// restarted if the next filter in the chain returns e.g.
+		// LZMA_MEM_ERROR.
+		memcpy(out + *out_pos, coder->buffer + coder->pos, buf_avail);
+		*out_pos += buf_avail;
+
+		// Copy/Encode/Decode more data to out[].
+		{
+			const lzma_ret ret = copy_or_code(coder, allocator,
+					in, in_pos, in_size,
+					out, out_pos, out_size, action);
+			assert(ret != LZMA_STREAM_END);
+			if (ret != LZMA_OK)
+				return ret;
+		}
+
+		// Filter out[].
+		size = *out_pos - out_start;
+		filtered = call_filter(coder, out + out_start, size);
+
+		unfiltered = size - filtered;
+		assert(unfiltered <= coder->allocated / 2);
+
+		// Now we can update coder->pos and coder->size, because
+		// the next coder in the chain (if any) was successful.
+		coder->pos = 0;
+		coder->size = unfiltered;
+
+		if (coder->end_was_reached) {
+			// The last byte has been copied to out[] already.
+			// They are left as is.
+			coder->size = 0;
+
+		} else if (unfiltered > 0) {
+			// There is unfiltered data left in out[]. Copy it to
+			// coder->buffer[] and rewind *out_pos appropriately.
+			*out_pos -= unfiltered;
+			memcpy(coder->buffer, out + *out_pos, unfiltered);
+		}
+	} else if (coder->pos > 0) {
+		memmove(coder->buffer, coder->buffer + coder->pos, buf_avail);
+		coder->size -= coder->pos;
+		coder->pos = 0;
+	}
+
+	assert(coder->pos == 0);
+
+	// If coder->buffer[] isn't empty, try to fill it by copying/decoding
+	// more data. Then filter coder->buffer[] and copy the successfully
+	// filtered data to out[]. It is probable, that some filtered and
+	// unfiltered data will be left to coder->buffer[].
+	if (coder->size > 0) {
+		{
+			const lzma_ret ret = copy_or_code(coder, allocator,
+					in, in_pos, in_size,
+					coder->buffer, &coder->size,
+					coder->allocated, action);
+			assert(ret != LZMA_STREAM_END);
+			if (ret != LZMA_OK)
+				return ret;
+		}
+
+		coder->filtered = call_filter(
+				coder, coder->buffer, coder->size);
+
+		// Everything is considered to be filtered if coder->buffer[]
+		// contains the last bytes of the data.
+		if (coder->end_was_reached)
+			coder->filtered = coder->size;
+
+		// Flush as much as possible.
+		lzma_bufcpy(coder->buffer, &coder->pos, coder->filtered,
+				out, out_pos, out_size);
+	}
+
+	// Check if we got everything done.
+	if (coder->end_was_reached && coder->pos == coder->size)
+		return LZMA_STREAM_END;
+
+	return LZMA_OK;
+}
+
+
+static void
+simple_coder_end(lzma_coder *coder, lzma_allocator *allocator)
+{
+	lzma_next_end(&coder->next, allocator);
+	lzma_free(coder->simple, allocator);
+	lzma_free(coder, allocator);
+	return;
+}
+
+
+static lzma_ret
+simple_coder_update(lzma_coder *coder, lzma_allocator *allocator,
+		const lzma_filter *filters_null lzma_attribute((__unused__)),
+		const lzma_filter *reversed_filters)
+{
+	// No update support, just call the next filter in the chain.
+	return lzma_next_filter_update(
+			&coder->next, allocator, reversed_filters + 1);
+}
+
+
+extern lzma_ret
+lzma_simple_coder_init(lzma_next_coder *next, lzma_allocator *allocator,
+		const lzma_filter_info *filters,
+		size_t (*filter)(lzma_simple *simple, uint32_t now_pos,
+			bool is_encoder, uint8_t *buffer, size_t size),
+		size_t simple_size, size_t unfiltered_max,
+		uint32_t alignment, bool is_encoder)
+{
+	// Allocate memory for the lzma_coder structure if needed.
+	if (next->coder == NULL) {
+		// Here we allocate space also for the temporary buffer. We
+		// need twice the size of unfiltered_max, because then it
+		// is always possible to filter at least unfiltered_max bytes
+		// more data in coder->buffer[] if it can be filled completely.
+		next->coder = lzma_alloc(sizeof(lzma_coder)
+				+ 2 * unfiltered_max, allocator);
+		if (next->coder == NULL)
+			return LZMA_MEM_ERROR;
+
+		next->code = &simple_code;
+		next->end = &simple_coder_end;
+		next->update = &simple_coder_update;
+
+		next->coder->next = LZMA_NEXT_CODER_INIT;
+		next->coder->filter = filter;
+		next->coder->allocated = 2 * unfiltered_max;
+
+		// Allocate memory for filter-specific data structure.
+		if (simple_size > 0) {
+			next->coder->simple = lzma_alloc(
+					simple_size, allocator);
+			if (next->coder->simple == NULL)
+				return LZMA_MEM_ERROR;
+		} else {
+			next->coder->simple = NULL;
+		}
+	}
+
+	if (filters[0].options != NULL) {
+		const lzma_options_bcj *simple = filters[0].options;
+		next->coder->now_pos = simple->start_offset;
+		if (next->coder->now_pos & (alignment - 1))
+			return LZMA_OPTIONS_ERROR;
+	} else {
+		next->coder->now_pos = 0;
+	}
+
+	// Reset variables.
+	next->coder->is_encoder = is_encoder;
+	next->coder->end_was_reached = false;
+	next->coder->pos = 0;
+	next->coder->filtered = 0;
+	next->coder->size = 0;
+
+	return lzma_next_filter_init(
+			&next->coder->next, allocator, filters + 1);
+}
diff --git a/Utilities/cmliblzma/liblzma/simple/simple_coder.h b/Utilities/cmliblzma/liblzma/simple/simple_coder.h
new file mode 100644
index 0000000..0952fad
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/simple/simple_coder.h
@@ -0,0 +1,60 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       simple_coder.h
+/// \brief      Wrapper for simple filters
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#ifndef LZMA_SIMPLE_CODER_H
+#define LZMA_SIMPLE_CODER_H
+
+#include "common.h"
+
+
+extern lzma_ret lzma_simple_x86_encoder_init(lzma_next_coder *next,
+		lzma_allocator *allocator, const lzma_filter_info *filters);
+
+extern lzma_ret lzma_simple_x86_decoder_init(lzma_next_coder *next,
+		lzma_allocator *allocator, const lzma_filter_info *filters);
+
+
+extern lzma_ret lzma_simple_powerpc_encoder_init(lzma_next_coder *next,
+		lzma_allocator *allocator, const lzma_filter_info *filters);
+
+extern lzma_ret lzma_simple_powerpc_decoder_init(lzma_next_coder *next,
+		lzma_allocator *allocator, const lzma_filter_info *filters);
+
+
+extern lzma_ret lzma_simple_ia64_encoder_init(lzma_next_coder *next,
+		lzma_allocator *allocator, const lzma_filter_info *filters);
+
+extern lzma_ret lzma_simple_ia64_decoder_init(lzma_next_coder *next,
+		lzma_allocator *allocator, const lzma_filter_info *filters);
+
+
+extern lzma_ret lzma_simple_arm_encoder_init(lzma_next_coder *next,
+		lzma_allocator *allocator, const lzma_filter_info *filters);
+
+extern lzma_ret lzma_simple_arm_decoder_init(lzma_next_coder *next,
+		lzma_allocator *allocator, const lzma_filter_info *filters);
+
+
+extern lzma_ret lzma_simple_armthumb_encoder_init(lzma_next_coder *next,
+		lzma_allocator *allocator, const lzma_filter_info *filters);
+
+extern lzma_ret lzma_simple_armthumb_decoder_init(lzma_next_coder *next,
+		lzma_allocator *allocator, const lzma_filter_info *filters);
+
+
+extern lzma_ret lzma_simple_sparc_encoder_init(lzma_next_coder *next,
+		lzma_allocator *allocator, const lzma_filter_info *filters);
+
+extern lzma_ret lzma_simple_sparc_decoder_init(lzma_next_coder *next,
+		lzma_allocator *allocator, const lzma_filter_info *filters);
+
+#endif
diff --git a/Utilities/cmliblzma/liblzma/simple/simple_decoder.c b/Utilities/cmliblzma/liblzma/simple/simple_decoder.c
new file mode 100644
index 0000000..034e158
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/simple/simple_decoder.c
@@ -0,0 +1,41 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       simple_decoder.c
+/// \brief      Properties decoder for simple filters
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "simple_decoder.h"
+
+
+extern lzma_ret
+lzma_simple_props_decode(void **options, lzma_allocator *allocator,
+		const uint8_t *props, size_t props_size)
+{
+	lzma_options_bcj *opt;
+
+	if (props_size == 0)
+		return LZMA_OK;
+
+	if (props_size != 4)
+		return LZMA_OPTIONS_ERROR;
+
+	opt = lzma_alloc(sizeof(lzma_options_bcj), allocator);
+	if (opt == NULL)
+		return LZMA_MEM_ERROR;
+
+	opt->start_offset = unaligned_read32le(props);
+
+	// Don't leave an options structure allocated if start_offset is zero.
+	if (opt->start_offset == 0)
+		lzma_free(opt, allocator);
+	else
+		*options = opt;
+
+	return LZMA_OK;
+}
diff --git a/Utilities/cmliblzma/liblzma/simple/simple_decoder.h b/Utilities/cmliblzma/liblzma/simple/simple_decoder.h
new file mode 100644
index 0000000..b8bf590
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/simple/simple_decoder.h
@@ -0,0 +1,22 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       simple_decoder.h
+/// \brief      Properties decoder for simple filters
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#ifndef LZMA_SIMPLE_DECODER_H
+#define LZMA_SIMPLE_DECODER_H
+
+#include "simple_coder.h"
+
+extern lzma_ret lzma_simple_props_decode(
+		void **options, lzma_allocator *allocator,
+		const uint8_t *props, size_t props_size);
+
+#endif
diff --git a/Utilities/cmliblzma/liblzma/simple/simple_encoder.c b/Utilities/cmliblzma/liblzma/simple/simple_encoder.c
new file mode 100644
index 0000000..8aa463b
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/simple/simple_encoder.c
@@ -0,0 +1,38 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       simple_encoder.c
+/// \brief      Properties encoder for simple filters
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "simple_encoder.h"
+
+
+extern lzma_ret
+lzma_simple_props_size(uint32_t *size, const void *options)
+{
+	const lzma_options_bcj *const opt = options;
+	*size = (opt == NULL || opt->start_offset == 0) ? 0 : 4;
+	return LZMA_OK;
+}
+
+
+extern lzma_ret
+lzma_simple_props_encode(const void *options, uint8_t *out)
+{
+	const lzma_options_bcj *const opt = options;
+
+	// The default start offset is zero, so we don't need to store any
+	// options unless the start offset is non-zero.
+	if (opt == NULL || opt->start_offset == 0)
+		return LZMA_OK;
+
+	unaligned_write32le(out, opt->start_offset);
+
+	return LZMA_OK;
+}
diff --git a/Utilities/cmliblzma/liblzma/simple/simple_encoder.h b/Utilities/cmliblzma/liblzma/simple/simple_encoder.h
new file mode 100644
index 0000000..1cee482
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/simple/simple_encoder.h
@@ -0,0 +1,23 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       simple_encoder.c
+/// \brief      Properties encoder for simple filters
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#ifndef LZMA_SIMPLE_ENCODER_H
+#define LZMA_SIMPLE_ENCODER_H
+
+#include "simple_coder.h"
+
+
+extern lzma_ret lzma_simple_props_size(uint32_t *size, const void *options);
+
+extern lzma_ret lzma_simple_props_encode(const void *options, uint8_t *out);
+
+#endif
diff --git a/Utilities/cmliblzma/liblzma/simple/simple_private.h b/Utilities/cmliblzma/liblzma/simple/simple_private.h
new file mode 100644
index 0000000..fcf9f7c
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/simple/simple_private.h
@@ -0,0 +1,75 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       simple_private.h
+/// \brief      Private definitions for so called simple filters
+//
+//  Author:     Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#ifndef LZMA_SIMPLE_PRIVATE_H
+#define LZMA_SIMPLE_PRIVATE_H
+
+#include "simple_coder.h"
+
+
+typedef struct lzma_simple_s lzma_simple;
+
+struct lzma_coder_s {
+	/// Next filter in the chain
+	lzma_next_coder next;
+
+	/// True if the next coder in the chain has returned LZMA_STREAM_END.
+	bool end_was_reached;
+
+	/// True if filter() should encode the data; false to decode.
+	/// Currently all simple filters use the same function for encoding
+	/// and decoding, because the difference between encoders and decoders
+	/// is very small.
+	bool is_encoder;
+
+	/// Pointer to filter-specific function, which does
+	/// the actual filtering.
+	size_t (*filter)(lzma_simple *simple, uint32_t now_pos,
+			bool is_encoder, uint8_t *buffer, size_t size);
+
+	/// Pointer to filter-specific data, or NULL if filter doesn't need
+	/// any extra data.
+	lzma_simple *simple;
+
+	/// The lowest 32 bits of the current position in the data. Most
+	/// filters need this to do conversions between absolute and relative
+	/// addresses.
+	uint32_t now_pos;
+
+	/// Size of the memory allocated for the buffer.
+	size_t allocated;
+
+	/// Flushing position in the temporary buffer. buffer[pos] is the
+	/// next byte to be copied to out[].
+	size_t pos;
+
+	/// buffer[filtered] is the first unfiltered byte. When pos is smaller
+	/// than filtered, there is unflushed filtered data in the buffer.
+	size_t filtered;
+
+	/// Total number of bytes (both filtered and unfiltered) currently
+	/// in the temporary buffer.
+	size_t size;
+
+	/// Temporary buffer
+	uint8_t buffer[];
+};
+
+
+extern lzma_ret lzma_simple_coder_init(lzma_next_coder *next,
+		lzma_allocator *allocator, const lzma_filter_info *filters,
+		size_t (*filter)(lzma_simple *simple, uint32_t now_pos,
+			bool is_encoder, uint8_t *buffer, size_t size),
+		size_t simple_size, size_t unfiltered_max,
+		uint32_t alignment, bool is_encoder);
+
+#endif
diff --git a/Utilities/cmliblzma/liblzma/simple/sparc.c b/Utilities/cmliblzma/liblzma/simple/sparc.c
new file mode 100644
index 0000000..0ddd2ac
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/simple/sparc.c
@@ -0,0 +1,82 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       sparc.c
+/// \brief      Filter for SPARC binaries
+///
+//  Authors:    Igor Pavlov
+//              Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "simple_private.h"
+
+
+static size_t
+sparc_code(lzma_simple *simple lzma_attribute((__unused__)),
+		uint32_t now_pos, bool is_encoder,
+		uint8_t *buffer, size_t size)
+{
+	size_t i;
+	for (i = 0; i + 4 <= size; i += 4) {
+
+		if ((buffer[i] == 0x40 && (buffer[i + 1] & 0xC0) == 0x00)
+				|| (buffer[i] == 0x7F
+				&& (buffer[i + 1] & 0xC0) == 0xC0)) {
+
+			uint32_t dest;
+
+			uint32_t src = ((uint32_t)buffer[i + 0] << 24)
+					| ((uint32_t)buffer[i + 1] << 16)
+					| ((uint32_t)buffer[i + 2] << 8)
+					| ((uint32_t)buffer[i + 3]);
+
+			src <<= 2;
+
+			if (is_encoder)
+				dest = now_pos + (uint32_t)(i) + src;
+			else
+				dest = src - (now_pos + (uint32_t)(i));
+
+			dest >>= 2;
+
+			dest = (((0 - ((dest >> 22) & 1)) << 22) & 0x3FFFFFFF)
+					| (dest & 0x3FFFFF)
+					| 0x40000000;
+
+			buffer[i + 0] = (uint8_t)(dest >> 24);
+			buffer[i + 1] = (uint8_t)(dest >> 16);
+			buffer[i + 2] = (uint8_t)(dest >> 8);
+			buffer[i + 3] = (uint8_t)(dest);
+		}
+	}
+
+	return i;
+}
+
+
+static lzma_ret
+sparc_coder_init(lzma_next_coder *next, lzma_allocator *allocator,
+		const lzma_filter_info *filters, bool is_encoder)
+{
+	return lzma_simple_coder_init(next, allocator, filters,
+			&sparc_code, 0, 4, 4, is_encoder);
+}
+
+
+extern lzma_ret
+lzma_simple_sparc_encoder_init(lzma_next_coder *next,
+		lzma_allocator *allocator, const lzma_filter_info *filters)
+{
+	return sparc_coder_init(next, allocator, filters, true);
+}
+
+
+extern lzma_ret
+lzma_simple_sparc_decoder_init(lzma_next_coder *next,
+		lzma_allocator *allocator, const lzma_filter_info *filters)
+{
+	return sparc_coder_init(next, allocator, filters, false);
+}
diff --git a/Utilities/cmliblzma/liblzma/simple/x86.c b/Utilities/cmliblzma/liblzma/simple/x86.c
new file mode 100644
index 0000000..101d8ed
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/simple/x86.c
@@ -0,0 +1,161 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file       x86.c
+/// \brief      Filter for x86 binaries (BCJ filter)
+///
+//  Authors:    Igor Pavlov
+//              Lasse Collin
+//
+//  This file has been put into the public domain.
+//  You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "simple_private.h"
+
+
+#define Test86MSByte(b) ((b) == 0 || (b) == 0xFF)
+
+
+struct lzma_simple_s {
+	uint32_t prev_mask;
+	uint32_t prev_pos;
+};
+
+
+static size_t
+x86_code(lzma_simple *simple, uint32_t now_pos, bool is_encoder,
+		uint8_t *buffer, size_t size)
+{
+	static const bool MASK_TO_ALLOWED_STATUS[8]
+		= { true, true, true, false, true, false, false, false };
+
+	static const uint32_t MASK_TO_BIT_NUMBER[8]
+			= { 0, 1, 2, 2, 3, 3, 3, 3 };
+
+	uint32_t prev_mask = simple->prev_mask;
+	uint32_t prev_pos = simple->prev_pos;
+
+	size_t limit;
+	size_t buffer_pos;
+
+	if (size < 5)
+		return 0;
+
+	if (now_pos - prev_pos > 5)
+		prev_pos = now_pos - 5;
+
+	limit = size - 5;
+	buffer_pos = 0;
+
+	while (buffer_pos <= limit) {
+		uint32_t offset;
+		uint32_t i;
+
+		uint8_t b = buffer[buffer_pos];
+		if (b != 0xE8 && b != 0xE9) {
+			++buffer_pos;
+			continue;
+		}
+
+		offset = now_pos + (uint32_t)(buffer_pos)
+				- prev_pos;
+		prev_pos = now_pos + (uint32_t)(buffer_pos);
+
+		if (offset > 5) {
+			prev_mask = 0;
+		} else {
+			for (i = 0; i < offset; ++i) {
+				prev_mask &= 0x77;
+				prev_mask <<= 1;
+			}
+		}
+
+		b = buffer[buffer_pos + 4];
+
+		if (Test86MSByte(b)
+			&& MASK_TO_ALLOWED_STATUS[(prev_mask >> 1) & 0x7]
+				&& (prev_mask >> 1) < 0x10) {
+
+			uint32_t src = ((uint32_t)(b) << 24)
+				| ((uint32_t)(buffer[buffer_pos + 3]) << 16)
+				| ((uint32_t)(buffer[buffer_pos + 2]) << 8)
+				| (buffer[buffer_pos + 1]);
+
+			uint32_t dest;
+			while (true) {
+				uint32_t i;
+
+				if (is_encoder)
+					dest = src + (now_pos + (uint32_t)(
+							buffer_pos) + 5);
+				else
+					dest = src - (now_pos + (uint32_t)(
+							buffer_pos) + 5);
+
+				if (prev_mask == 0)
+					break;
+
+				i = MASK_TO_BIT_NUMBER[prev_mask >> 1];
+
+				b = (uint8_t)(dest >> (24 - i * 8));
+
+				if (!Test86MSByte(b))
+					break;
+
+				src = dest ^ ((1 << (32 - i * 8)) - 1);
+			}
+
+			buffer[buffer_pos + 4]
+					= (uint8_t)(~(((dest >> 24) & 1) - 1));
+			buffer[buffer_pos + 3] = (uint8_t)(dest >> 16);
+			buffer[buffer_pos + 2] = (uint8_t)(dest >> 8);
+			buffer[buffer_pos + 1] = (uint8_t)(dest);
+			buffer_pos += 5;
+			prev_mask = 0;
+
+		} else {
+			++buffer_pos;
+			prev_mask |= 1;
+			if (Test86MSByte(b))
+				prev_mask |= 0x10;
+		}
+	}
+
+	simple->prev_mask = prev_mask;
+	simple->prev_pos = prev_pos;
+
+	return buffer_pos;
+}
+
+
+static lzma_ret
+x86_coder_init(lzma_next_coder *next, lzma_allocator *allocator,
+		const lzma_filter_info *filters, bool is_encoder)
+{
+	const lzma_ret ret = lzma_simple_coder_init(next, allocator, filters,
+			&x86_code, sizeof(lzma_simple), 5, 1, is_encoder);
+
+	if (ret == LZMA_OK) {
+		next->coder->simple->prev_mask = 0;
+		next->coder->simple->prev_pos = (uint32_t)(-5);
+	}
+
+	return ret;
+}
+
+
+extern lzma_ret
+lzma_simple_x86_encoder_init(lzma_next_coder *next, lzma_allocator *allocator,
+		const lzma_filter_info *filters)
+{
+	return x86_coder_init(next, allocator, filters, true);
+}
+
+
+extern lzma_ret
+lzma_simple_x86_decoder_init(lzma_next_coder *next, lzma_allocator *allocator,
+		const lzma_filter_info *filters)
+{
+	return x86_coder_init(next, allocator, filters, false);
+}
diff --git a/bootstrap b/bootstrap
index a3cc0a3..b09023d 100755
--- a/bootstrap
+++ b/bootstrap
@@ -1477,9 +1477,11 @@
 # When bootstrapping on MinGW with MSYS we must convert the source
 # directory to a windows path.
 if ${cmake_system_mingw}; then
-    cmake_root_dir=`cd "${cmake_source_dir}"; pwd -W`
+    CMAKE_BOOTSTRAP_SOURCE_DIR=`cd "${cmake_source_dir}"; pwd -W`
+    CMAKE_BOOTSTRAP_BINARY_DIR=`cd "${cmake_binary_dir}"; pwd -W`
 else
-    cmake_root_dir="${cmake_source_dir}"
+    CMAKE_BOOTSTRAP_SOURCE_DIR="${cmake_source_dir}"
+    CMAKE_BOOTSTRAP_BINARY_DIR="${cmake_binary_dir}"
 fi
 
 # Write CMake version
@@ -1487,7 +1489,8 @@
 cmake_report cmVersionConfig.h${_tmp} "#define CMake_VERSION_MINOR ${cmake_version_minor}"
 cmake_report cmVersionConfig.h${_tmp} "#define CMake_VERSION_PATCH ${cmake_version_patch}"
 cmake_report cmVersionConfig.h${_tmp} "#define CMake_VERSION \"${cmake_version}\""
-cmake_report cmConfigure.h${_tmp} "#define CMAKE_ROOT_DIR \"${cmake_root_dir}\""
+cmake_report cmConfigure.h${_tmp} "#define CMAKE_BOOTSTRAP_SOURCE_DIR \"${CMAKE_BOOTSTRAP_SOURCE_DIR}\""
+cmake_report cmConfigure.h${_tmp} "#define CMAKE_BOOTSTRAP_BINARY_DIR \"${CMAKE_BOOTSTRAP_BINARY_DIR}\""
 cmake_report cmConfigure.h${_tmp} "#define CMAKE_DATA_DIR \"/bootstrap-not-insalled\""
 cmake_report cmConfigure.h${_tmp} "#define CMAKE_BOOTSTRAP"